package com.xinhe.web.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.BusinessException;
import com.xinhe.web.common.Result;
import com.xinhe.web.common.SimplePage;
import com.xinhe.web.entity.*;
import com.xinhe.web.enums.Constant;
import com.xinhe.web.excl.MemberEasyView;
import com.xinhe.web.excl.MemberRecommendationEasyView;
import com.xinhe.web.reposity.*;
import com.xinhe.web.request.MemberModel;
import com.xinhe.web.request.MemberQuery;
import com.xinhe.web.request.MemberTeamStatisticsView;
import com.xinhe.web.response.*;
import com.xinhe.web.session.UserSessionManager;
import com.xinhe.web.session.UserSessionView;
import com.xinhe.web.util.CharCodeUtil;
import com.xinhe.web.util.HttpClientUtil;
import com.xinhe.web.util.Snowflake;
import com.xinhe.web.util.ThreadPoolUtil;
import com.xinhe.web.vo.UserRegisterModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MemberService {
    public static final String appid = "wx2425d0af98810b00";
    public static final String appsecret = "f74746117f13a69ef272055921e81b3f";


    //查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;
    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }
    @Autowired
    MemberRepository memberRepository;
    @Autowired
    AssetDetailRepository assetDetailRepository;
    @Autowired
    AuthUserRepository authUserRepository;
    @Autowired
    AssetCountRepository assetCountRepository;
    @Autowired
    WithdrawalsRecordRepository withdrawalsRecordRepository;
    @Autowired
    AdoptedTreeOrderRepository adoptedTreeOrderRepository;
    @Autowired
    ValueConfigRepository valueConfigRepository;
    @Autowired
    AssetCountService assetCountService;
    @Autowired
    WeixinUserRepository weixinUserRepository;
    @Autowired
    UserService userService;
    @Autowired
    UserSessionManager userSessionManager;
    @Autowired
    AliyunService aliyunService;


    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    public QueryResults<MemberView> pageMember(String queryWord,
                                           String isCheckStatus,
                                           int pageNum, int pageSize) {
        QMember qMember = QMember.member;
        QMember qMember2 = new QMember("member2"); ;
        QServiceCenter qServiceCenter = QServiceCenter.serviceCenter;
        QIdentity qIdentity = QIdentity.identity;
        BooleanBuilder builder = new BooleanBuilder();
        OrderSpecifier<Date> sort = qMember.createTime.desc();
        builder.and(qMember.removed.eq(0));
        if (StringUtils.isNotEmpty(queryWord)) {
            builder.and(qMember.name.contains(queryWord).or(qMember.mobile.contains(queryWord)));
        }
        if (!Objects.isNull(isCheckStatus)) {
            builder.and(qMember.memberStatus.contains(isCheckStatus));
        }
        return queryFactory.select(
                        Projections.bean(
                                MemberView.class,
                                qMember.name,
                                qMember.removed,
                                qMember.memberStatus,
                                qMember.id,
                                qMember.createTime,
                                qMember.remark,
                                qMember.versionNum,
                                qMember.fServiceId,
                                qMember.fUserId,
                                qMember.iconPath,
                                qMember.nickname,
                                qMember.mobile,
                                qMember.code,
                                qMember.parentCode,
                                qMember.gender,
                                qMember.level,
                                qMember.role,
                                qMember.roleTwo,
                                qMember.adoptionDate,
                                qMember.adoptionNum,
                                qMember.newReference,
                                qMember.identifying,
                                qMember.twoThawNo,
                                qMember.threeThawNo,
                                qMember.twoThawAdopted,
                                qMember.threeThawAdopted,
                                qMember.isImportMember,
                                qMember.disengageNo,
                                qMember2.name.as("parentName"),
                                qMember2.mobile.as("parentMobile"),
                                qServiceCenter.name.as("serviceName"),
                                qIdentity.checkStatus.as("checkStatus")
                        )
                ).from(qMember)
                 .leftJoin(qMember2).on(qMember.parentCode.eq(qMember2.code))
                 .leftJoin(qServiceCenter).on(qMember.fServiceId.eq(qServiceCenter.id))
                 .leftJoin(qIdentity).on(qMember.fUserId.eq(qIdentity.fUserId).and(qIdentity.checkStatus.eq("SUCCESS")))
                .where(builder).offset(pageNum * pageSize).limit(pageSize).orderBy(sort).fetchResults();
    }
    public List<MemberView> pageMemberList() {
        QMember qMember = QMember.member;
        QMember qMember2 = new QMember("member2");
        QServiceCenter qServiceCenter = QServiceCenter.serviceCenter;
        QIdentity qIdentity = QIdentity.identity;
        BooleanBuilder builder = new BooleanBuilder();
        OrderSpecifier<Date> sort = qMember.createTime.desc();
        builder.and(qMember.removed.eq(0));
        return queryFactory.select(
                        Projections.bean(
                                MemberView.class,
                                qMember.name,
                                qMember.removed,
                                qMember.memberStatus,
                                qMember.id,
                                qMember.createTime,
                                qMember.remark,
                                qMember.versionNum,
                                qMember.fServiceId,
                                qMember.fUserId,
                                qMember.iconPath,
                                qMember.nickname,
                                qMember.mobile,
                                qMember.code,
                                qMember.parentCode,
                                qMember.gender,
                                qMember.level,
                                qMember.role,
                                qMember.roleTwo,
                                qMember.adoptionDate,
                                qMember.adoptionNum,
                                qMember.newReference,
                                qMember.identifying,
                                qMember.twoThawNo,
                                qMember.threeThawNo,
                                qMember.twoThawAdopted,
                                qMember.threeThawAdopted,
                                qMember.isImportMember,
                                qMember.disengageNo,
                                qMember2.name.as("parentName"),
                                qMember2.mobile.as("parentMobile"),
                                qServiceCenter.name.as("serviceName"),
                                qIdentity.checkStatus.as("checkStatus")
                        )
                ).from(qMember)
                .leftJoin(qMember2).on(qMember.parentCode.eq(qMember2.code))
                .leftJoin(qServiceCenter).on(qMember.fServiceId.eq(qServiceCenter.id))
                .leftJoin(qIdentity).on(qMember.fUserId.eq(qIdentity.fUserId).and(qIdentity.checkStatus.eq("SUCCESS")))
                .where(builder).orderBy(sort).fetch();
    }
    @Transactional(rollbackFor = Exception.class)
    public void easyMemberExcel(HttpServletResponse response) {
        String path = "";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        List<MemberView> all = pageMemberList();
        if (CollectionUtils.isEmpty(all)) {
            throw new BusinessException(10003,"你没有可以导出的数据");
        }
        List<MemberEasyView> easyViews = new ArrayList<>();
        try {
            for (MemberView view : all) {
                MemberEasyView memberEasyView = new MemberEasyView();
                if (view.getGender().intValue() == 0) {
                    memberEasyView.setGender("男");
                } else {
                    memberEasyView.setGender("女");
                }
                memberEasyView.setName(view.getName());
                memberEasyView.setParentName(view.getParentName());
                memberEasyView.setParentMobile(view.getParentMobile());
                memberEasyView.setMobile(view.getMobile());
                memberEasyView.setAdoptionNum(view.getAdoptionNum());
                memberEasyView.setServiceName(view.getServiceName());
                memberEasyView.setMemberStatus(view.getMemberStatus());
                memberEasyView.setLevel(view.getLevel());
                if ("创始人".equals(view.getRole())) {
                    memberEasyView.setRole(view.getRole());
                }
                if ("智慧合伙人".equals(view.getRoleTwo())) {
                    memberEasyView.setRoleTwo(view.getRoleTwo());
                }
                memberEasyView.setCreateTime(simpleDateFormat.format(view.getCreateTime()));
                memberEasyView.setThreeThawNo(view.getThreeThawNo());
                memberEasyView.setTwoThawNo(view.getTwoThawNo());
                memberEasyView.setTwoThawAdopted(view.getTwoThawAdopted());
                memberEasyView.setThreeThawAdopted(view.getThreeThawAdopted());
                easyViews.add(memberEasyView);
            }
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("会员列表"+simpleDateFormat.format(new Date()), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //   Student.class 是按导出类  data()应为数据库查询数据，这里只是模拟
            EasyExcel.write(response.getOutputStream(), MemberEasyView.class).sheet("会员列表").doWrite(easyViews);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public Result addMemberBalance(Long userId, String tradeType, BigDecimal money, String remark) {
        if (money.compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessException(2005,"金额不能为零");
        }
        Member member = memberRepository.findByUserId(userId);
        if (null == member) {
            throw new BusinessException(2003,"会员不存在");
        }
        if (null == tradeType) {
            throw new BusinessException(2004,"请选择类型");
        }
        AssetDetail assetDetail = new AssetDetail();
        assetDetail.setId(Snowflake.generateId());
        assetDetail.setAssetType("RMB");
        assetDetail.setfUserId(userId);
        assetDetail.setDtype("AssetDetail");
        assetDetail.setTradeType(tradeType);
        assetDetail.setTradeAmount(money);
        assetDetail.setRemainder(money);//todo 不知道
        assetDetail.setfBusinessId(Snowflake.generateId());//todo 不知道
        assetDetailRepository.save(assetDetail);
        return Result.ok();
    }
    @Transactional(rollbackFor = Exception.class)
    public Result sendSeedYunChaSeed(Long userId, BigDecimal additionalYunChaSeed) {
        if (null == userId) {
            throw new BusinessException(3001,"userId为空");
        }
        if (additionalYunChaSeed.compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessException(3002,"赠送数量不能小于0");
        }
        AssetDetail assetDetail = new AssetDetail();
        assetDetail.setId(Snowflake.generateId());
        assetDetail.setfUserId(userId);
        assetDetail.setDtype("AssetDetail");
        assetDetail.setTradeType("ADDITIONAL_GIFT_YUN_CHA_SEED");
        assetDetail.setTradeAmount(additionalYunChaSeed);
        assetDetail.setRemainder(additionalYunChaSeed);//todo 不知道
        assetDetail.setfBusinessId(Snowflake.generateId());//todo 不知道
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse = format.parse("2024-01-01");
            if (parse.compareTo(new Date()) > 0) {
                assetDetail.setAssetType("YUN_CHA_SEED");
            } else {
                assetDetail.setAssetType("NEW_YUN_CHA_SEED");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        assetDetailRepository.save(assetDetail);
        return Result.ok();
    }
    @Transactional
    public Result updateIdentifying(Long userId) {
        Member member = memberRepository.findByUserId(userId);
        member.setIdentifying(Integer.valueOf((member.getIdentifying().intValue() == 0) ? 1 : 0));
        memberRepository.saveAndFlush(member);
        return Result.ok();
    }
    @Transactional
    public Result updateMemberRole(Long userId, String role) {
        Member member = memberRepository.findByUserId(userId);
        if (member != null) {
            member.setRole(role);
            if (!Constant.FOUNDER.equals(role)) {
                //member.setFServiceId(null);不能让服务中心丢失
                member.setParentCode(member.getNewReference());
            } else if (member.getIsImportMember().intValue() == 0) {
                member.setParentCode(null);
            }
            memberRepository.saveAndFlush(member);
        }
        return Result.ok();
    }
    @Transactional
    public Result updateMemberRoleTwo(Long userId, String role) {
        Member member = memberRepository.findByUserId(userId);
        if (member != null) {
            member.setRoleTwo(role);
            memberRepository.saveAndFlush(member);
        }
        return Result.ok();
    }
    @Transactional
    public Result updateMemberStatus(Long userId, String status) {
        Member member = memberRepository.findByUserId(userId);
        member.setMemberStatus(status);
        memberRepository.saveAndFlush(member);
        return Result.ok();
    }
    @Transactional
    public Result memberRegistration(String name, String mobile, String parentCode) {
        String i = "^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\\d{8}$";
        Pattern compile = Pattern.compile(i);
        if (!compile.matcher(mobile).matches()) {
            throw new BusinessException(4001,"手机格式不正确");
        }
        Member member = memberRepository.findByMobile(mobile);
        if (null != member) {
            throw new BusinessException(4002,"用户已存在");
        }
        if (StringUtils.isNotBlank(parentCode)) {
            Member byCode = memberRepository.findByCode(parentCode);
            if (null == byCode) {
                throw new BusinessException(4003,"推荐人不存在");
            }
        }
        //往auth_user插入记录
        User authUser = new User();
        authUser.setCreateTime(new Date());
        authUser.setPhoneNumber(mobile);
        authUser.setId(Snowflake.generateId());
        User save = authUserRepository.save(authUser);
        member = new Member();
        member.setFUserId(save.getId());
        if (StringUtils.isNotBlank(parentCode)) {
            Member parent = memberRepository.findByCode(parentCode);
            if (parent != null) {
                member.setFServiceId(parent.getFServiceId());
                member.setParentCode(parent.getCode());
                member.setNewReference(parent.getCode());
            }
        }
        member.setGender(Integer.valueOf(0));
        member.setLevel("COMMON");
        member.setRoleTwo("NO");
        member.setRole("NO");
        member.setMemberStatus("NORMAL");
        member.setCode(mobile);
        member.setMobile(mobile);
        member.setIsImportMember(Integer.valueOf(1));
        member.setName(name);
        member.setPassword(DigestUtils.md5Hex("123456"));
        member.setNickname(mobile.replaceAll("(\\d{3})\\d{6}(\\d{2})", "$1******$2"));
        member.setIconPath("https://xhyp.quexiaoer.cn/upload/default/default_avatar.png");
        memberRepository.save(member);
        //这里保存了7中资产类型的记录，初始余额先都给0
        List<AssetCount> list = assetCountSave(member.getFUserId());
        assetCountRepository.saveAll(list);
        return Result.ok();
    }

    private List<AssetCount> assetCountSave(Long userId) {
        List<AssetCount> list = new ArrayList<>();
        AssetCount assetCount = new AssetCount();
        assetCount.setfUserId(userId);
        assetCount.setType("RMB");
        assetCount.setId(Snowflake.generateId());
        assetCount.setAvailable(new BigDecimal(0));
        assetCount.setRemainder(new BigDecimal(0));
        assetCount.setFrozen(new BigDecimal(0));
        assetCount.setTotal(new BigDecimal(0));
        list.add(assetCount);

        AssetCount assetCount1 = new AssetCount();
        assetCount1.setfUserId(userId);
        assetCount1.setType("YUN_CHA_SEED");
        assetCount1.setId(Snowflake.generateId());
        assetCount1.setAvailable(new BigDecimal(0));
        assetCount1.setRemainder(new BigDecimal(0));
        assetCount1.setFrozen(new BigDecimal(0));
        assetCount1.setTotal(new BigDecimal(0));
        list.add(assetCount1);

        AssetCount assetCount2 = new AssetCount();
        assetCount2.setfUserId(userId);
        assetCount2.setType("NEW_YUN_CHA_SEED");
        assetCount2.setId(Snowflake.generateId());
        assetCount2.setAvailable(new BigDecimal(0));
        assetCount2.setRemainder(new BigDecimal(0));
        assetCount2.setFrozen(new BigDecimal(0));
        assetCount2.setTotal(new BigDecimal(0));
        list.add(assetCount2);

        AssetCount assetCount3 = new AssetCount();
        assetCount3.setfUserId(userId);
        assetCount3.setType("TEA_OIL_CARD");
        assetCount3.setId(Snowflake.generateId());
        assetCount3.setAvailable(new BigDecimal(0));
        assetCount3.setRemainder(new BigDecimal(0));
        assetCount3.setFrozen(new BigDecimal(0));
        assetCount3.setTotal(new BigDecimal(0));
        list.add(assetCount3);

        AssetCount assetCount4 = new AssetCount();
        assetCount4.setfUserId(userId);
        assetCount4.setType("CONSUMER_GOLD_RED_ENVELOPE");
        assetCount4.setId(Snowflake.generateId());
        assetCount4.setAvailable(new BigDecimal(0));
        assetCount4.setRemainder(new BigDecimal(0));
        assetCount4.setFrozen(new BigDecimal(0));
        assetCount4.setTotal(new BigDecimal(0));
        list.add(assetCount4);

        AssetCount assetCount5 = new AssetCount();
        assetCount5.setfUserId(userId);
        assetCount5.setType("UNFREEZING_CONSUMER_GOLD_RED_ENVELOPE");
        assetCount5.setId(Snowflake.generateId());
        assetCount5.setAvailable(new BigDecimal(0));
        assetCount5.setRemainder(new BigDecimal(0));
        assetCount5.setFrozen(new BigDecimal(0));
        assetCount5.setTotal(new BigDecimal(0));
        list.add(assetCount5);

        AssetCount assetCount6 = new AssetCount();
        assetCount6.setfUserId(userId);
        assetCount6.setType("TEA_OIL");
        assetCount6.setId(Snowflake.generateId());
        assetCount6.setAvailable(new BigDecimal(0));
        assetCount6.setRemainder(new BigDecimal(0));
        assetCount6.setFrozen(new BigDecimal(0));
        assetCount6.setTotal(new BigDecimal(0));
        list.add(assetCount6);
        return list;
    }
    public QueryResults<MemberRecommendationDetailsView> findByMemberRecommendation(String queryWord, Date startTime, Date endTime,
                                                                              int pageNum, int pageSize) {
        QMember qMember = QMember.member;
        QAssetDetail qAssetDetail = QAssetDetail.assetDetail;
        BooleanBuilder builder = new BooleanBuilder();
        OrderSpecifier<Date> sort = qMember.createTime.desc();
        builder.and(qMember.removed.eq(0));
        builder.and(qAssetDetail.assetType.eq("RMB"));
        builder.and(qAssetDetail.tradeType.eq("TWO_THAW_REWARD")
                .or(qAssetDetail.tradeType.eq("THREE_THAW_REWARD"))
                .or(qAssetDetail.tradeType.eq("FOUNDER_REWARDS"))
                .or(qAssetDetail.tradeType.eq("ADDITIONAL_REWARDS"))
        );
        if (StringUtils.isNotEmpty(queryWord)) {
            builder.and(qMember.name.contains(queryWord).or(qMember.mobile.contains(queryWord)));
        }
        if (!Objects.isNull(startTime) && !Objects.isNull(endTime)) {
            builder.and(qMember.createTime.between(startTime, endTime));
        }
        return queryFactory.select(
                        Projections.bean(
                                MemberRecommendationDetailsView.class,
                                qMember.name,
                                qMember.mobile,
                                qAssetDetail.createTime,
                                qAssetDetail.tradeAmount,
                                qAssetDetail.tradeType
                        )
                ).from(qMember)
                .leftJoin(qAssetDetail).on(qMember.fUserId.eq(qAssetDetail.fUserId).and(qAssetDetail.removed.eq(0)))
                .where(builder).offset(pageNum * pageSize).limit(pageSize).orderBy(sort).fetchResults();
    }
    public void easyMemberRecommendationExcel(String queryWord, Date startTime, Date endTime,
                                              int pageNum, int pageSize,HttpServletResponse response) {
        QMember qMember = QMember.member;
        QAssetDetail qAssetDetail = QAssetDetail.assetDetail;
        BooleanBuilder builder = new BooleanBuilder();
        OrderSpecifier<Date> sort = qMember.createTime.desc();
        builder.and(qMember.removed.eq(0));
        builder.and(qAssetDetail.assetType.eq("RMB"));
        builder.and(qAssetDetail.tradeType.eq("TWO_THAW_REWARD")
                .or(qAssetDetail.tradeType.eq("THREE_THAW_REWARD"))
                .or(qAssetDetail.tradeType.eq("FOUNDER_REWARDS"))
                .or(qAssetDetail.tradeType.eq("ADDITIONAL_REWARDS"))
        );
        if (StringUtils.isNotEmpty(queryWord)) {
            builder.and(qMember.name.contains(queryWord).or(qMember.mobile.contains(queryWord)));
        }
        if (!Objects.isNull(startTime) && !Objects.isNull(endTime)) {
            builder.and(qMember.createTime.between(startTime, endTime));
        }
        List<MemberRecommendationDetailsView> fetch = queryFactory.select(
                        Projections.bean(
                                MemberRecommendationDetailsView.class,
                                qMember.name,
                                qMember.mobile,
                                qAssetDetail.createTime,
                                qAssetDetail.tradeAmount,
                                qAssetDetail.tradeType
                        )
                ).from(qMember)
                .leftJoin(qAssetDetail).on(qMember.fUserId.eq(qAssetDetail.fUserId).and(qAssetDetail.removed.eq(0)))
                .where(builder).offset(pageNum * pageSize).limit(pageSize).orderBy(sort).fetch();
        List<MemberRecommendationEasyView> easyViews = new ArrayList<>();
        try {
            for (MemberRecommendationDetailsView view : fetch) {
                MemberRecommendationEasyView memberRecommendationEasyView = new MemberRecommendationEasyView();
                memberRecommendationEasyView.setName(view.getName());
                //memberRecommendationEasyView.setCreateTime(view.getCreateTime());
                memberRecommendationEasyView.setTradeAmount(view.getTradeAmount());
                memberRecommendationEasyView.setMobile(view.getMobile());
                memberRecommendationEasyView.setTradeType(view.getTradeType());
                easyViews.add(memberRecommendationEasyView);
            }
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("会员推荐明细"+simpleDateFormat.format(new Date()), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //   Student.class 是按导出类  data()应为数据库查询数据，这里只是模拟
            EasyExcel.write(response.getOutputStream(), MemberRecommendationEasyView.class).sheet("会员推荐明细").doWrite(easyViews);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public QueryResults<MemberAccountDetailsView> findByMemberAccountDetail(String queryWord, int pageNum, int pageSize) {
        QMember qMember = QMember.member;
        QAssetDetail qAssetDetail = QAssetDetail.assetDetail; ;
        QAssetCount qAssetCount = QAssetCount.assetCount;
        BooleanBuilder builder = new BooleanBuilder();
        OrderSpecifier<Date> sort = qMember.createTime.desc();
        builder.and(qMember.removed.eq(0));
        if (StringUtils.isNotEmpty(queryWord)) {
            builder.and(qMember.name.contains(queryWord).or(qMember.mobile.contains(queryWord)));
        }
        QueryResults<MemberAccountDetailsView> memberViewQueryResults = queryFactory.select(
                        Projections.bean(
                                MemberAccountDetailsView.class,
                                qMember.name,
                                qMember.mobile,
                                qMember.adoptionNum,
                                qMember.id,
                                qMember.fUserId
                        )
                ).from(qMember)
                .where(builder).offset(pageNum * pageSize).limit(pageSize).orderBy(sort).fetchResults();
        List<MemberAccountDetailsView> results = memberViewQueryResults.getResults();
        // 创建一个用于存储修改后元组对象的列表
        List<MemberAccountDetailsView> modifiedResults = new ArrayList<>();
        // 遍历分页记录，进行字段值重新赋值
        for (MemberAccountDetailsView memberAccountDetailsView : results) {
            //查询账户余额
            BigDecimal rmb = assetCountRepository.queryRmb(memberAccountDetailsView.getfUserId());
            //查询已提现总额
            BigDecimal withdrawalsMoney = withdrawalsRecordRepository.queryWithdrawalsMoney(memberAccountDetailsView.getfUserId());
            // 创建一个新的元组对象，并将修改后的字段值设置到新的元组对象中
            MemberAccountDetailsView newMemberAccountDetailsView = new MemberAccountDetailsView();
            BeanUtils.copyProperties(memberAccountDetailsView, newMemberAccountDetailsView);
            newMemberAccountDetailsView.setRmb(rmb);
            newMemberAccountDetailsView.setWithdrawalsMoney(withdrawalsMoney);
            // 将修改后的元组对象添加到列表中
            modifiedResults.add(newMemberAccountDetailsView);
        }
        // 创建一个新的QueryResults对象，包含修改后的分页记录
        QueryResults<MemberAccountDetailsView> modifiedQueryResults = new QueryResults<>(
                modifiedResults,
                memberViewQueryResults.getTotal(),
                memberViewQueryResults.getOffset(),
                memberViewQueryResults.getLimit()
        );
        return modifiedQueryResults;
    }
    public Result<MemberComprehensiveAnalysisView> comprehensiveAnalysis(Long serviceId ,int pageNum, int pageSize) {
        MemberComprehensiveAnalysisView memberComprehensiveAnalysisView = new MemberComprehensiveAnalysisView();
        int num = 0;
        BigDecimal money = BigDecimal.ZERO;
        int sum = 0;
        Integer mothMemberNo = Integer.valueOf(0);
        BigDecimal withdrawnAmount = BigDecimal.ZERO;
        BigDecimal AmountToWithdrawn = BigDecimal.ZERO;
        BigDecimal giveTeaOilCard = BigDecimal.ZERO;
        BigDecimal toBeTeaOilCard = BigDecimal.ZERO;
        BigDecimal honBao = BigDecimal.ZERO;
        BigDecimal toBeConsumedHonBao = BigDecimal.ZERO;
        BigDecimal sumYunChaSeed = BigDecimal.ZERO;
        BigDecimal toBeYunChaSeed = BigDecimal.ZERO;
        Integer toDayAdopted = Integer.valueOf(0);
        BigDecimal toDayAdoptedMoney = BigDecimal.ZERO;
        Integer thisMonthAdopted = Integer.valueOf(0);
        BigDecimal thisMonthAdoptedMoney = BigDecimal.ZERO;
        Integer lastAdopted = Integer.valueOf(0);
        BigDecimal lastAdoptedMoney = BigDecimal.ZERO;
        if (Objects.isNull(serviceId)) {
            sum = adoptedTreeOrderRepository.findByCompanySum();
            money = adoptedTreeOrderRepository.findByTotalMoney();
            List<Member> members = memberRepository.findAll();
            if (!CollectionUtils.isEmpty(members)){
                num += members.size();
            }
            mothMemberNo = memberRepository.findByThisMonthMember();
            withdrawnAmount = withdrawalsRecordRepository.findByThisMonthMoney();
            AmountToWithdrawn = assetDetailRepository.findByAmountToWithdrawn();
            giveTeaOilCard = assetDetailRepository.findByChaYouKa();
            toBeTeaOilCard = assetDetailRepository.findByToBeTeaOilCard();
            honBao = assetDetailRepository.findByHongBao();
            toBeConsumedHonBao = assetDetailRepository.findByToBeConsumedHonBao();
            sumYunChaSeed = assetDetailRepository.findBySumYunChaSeed();
            toBeYunChaSeed = assetDetailRepository.findByToBeYunChaSeed();
            toDayAdopted = adoptedTreeOrderRepository.findByToDayAdopted();
            toDayAdoptedMoney = adoptedTreeOrderRepository.findByToDayAdoptedMoney();
            thisMonthAdopted = adoptedTreeOrderRepository.findByThisMonthAdopted();
            thisMonthAdoptedMoney = adoptedTreeOrderRepository.findByThisMonthAdoptedMoney();
            lastAdopted = adoptedTreeOrderRepository.findByLastMonthAdopted();
            lastAdoptedMoney = adoptedTreeOrderRepository.findByLastMonthAdoptedMoney();
            memberComprehensiveAnalysisView.setAdoptedOrderNum(Integer.valueOf(sum));
            memberComprehensiveAnalysisView.setMoney(money);
            memberComprehensiveAnalysisView.setNum(Integer.valueOf(num));
            memberComprehensiveAnalysisView.setMothMemberNo(mothMemberNo);
            memberComprehensiveAnalysisView.setWithdrawnAmount(withdrawnAmount);
            memberComprehensiveAnalysisView.setAmountToWithdrawn(AmountToWithdrawn);
            memberComprehensiveAnalysisView.setGiveTeaOilCard(giveTeaOilCard);
            memberComprehensiveAnalysisView.setToBeTeaOilCard(toBeTeaOilCard);
            memberComprehensiveAnalysisView.setHonBao(honBao);
            memberComprehensiveAnalysisView.setToBeConsumedHonBao(toBeConsumedHonBao);
            memberComprehensiveAnalysisView.setSumYunChaSeed(sumYunChaSeed);
            memberComprehensiveAnalysisView.setToBeYunChaSeed(toBeYunChaSeed);
            memberComprehensiveAnalysisView.setTodayAdoptedNo(toDayAdopted);
            memberComprehensiveAnalysisView.setTodayAdoptedMoney(toDayAdoptedMoney);
            memberComprehensiveAnalysisView.setThisMonthAdoptedNo(thisMonthAdopted);
            memberComprehensiveAnalysisView.setThisMonthAdoptedMoney(thisMonthAdoptedMoney);
            memberComprehensiveAnalysisView.setLastMonthAdoptedNo(lastAdopted);
            memberComprehensiveAnalysisView.setLastMonthAdoptedMoney(lastAdoptedMoney);
        } else {
            List<Member> memberList = memberRepository.findByServiceId(serviceId);
            if (!CollectionUtils.isEmpty(memberList)) {
                for (Member member1 : memberList) {
                    MemberMonthView memberMonthView = adoptedTreeOrderRepository.findByServiceMember(member1.getFUserId());
                    if (null != memberMonthView) {
                        sum += memberMonthView.getSum().intValue();
                        money = money.add(memberMonthView.getSumMoney());
                        thisMonthAdopted = Integer.valueOf(thisMonthAdopted.intValue() + memberMonthView.getThisMonth().intValue());
                        lastAdopted = Integer.valueOf(lastAdopted.intValue() + memberMonthView.getLastMonth().intValue());
                        toDayAdopted = Integer.valueOf(toDayAdopted.intValue() + memberMonthView.getToDayAdopted().intValue());
                        toDayAdoptedMoney = toDayAdoptedMoney.add(memberMonthView.getToDayAdoptedMoney());
                        thisMonthAdoptedMoney = thisMonthAdoptedMoney.add(memberMonthView.getThisMonthAdoptedMoney());
                        lastAdoptedMoney = lastAdoptedMoney.add(memberMonthView.getLastAdoptedMoney());
                    }
                    MemberAccountDetailsView memberAccountDetailsViews = memberRepository.findByServiceIdAndAll(member1.getFUserId());
                    if (null != memberAccountDetailsViews) {
                        withdrawnAmount = withdrawnAmount.add(memberAccountDetailsViews.getWithdrawalsMoney());
                        AmountToWithdrawn = AmountToWithdrawn.add(memberAccountDetailsViews.getRmb());
                        giveTeaOilCard = giveTeaOilCard.add(memberAccountDetailsViews.getSumTeaOilCard());
                        toBeTeaOilCard = toBeTeaOilCard.add(memberAccountDetailsViews.getTeaOilCard());
                        honBao = honBao.add(memberAccountDetailsViews.getThawedConsumerGoldRedEnvelope());
                        toBeConsumedHonBao = toBeConsumedHonBao.add(memberAccountDetailsViews.getToThawedConsumerGoldRedEnvelope());
                        sumYunChaSeed = sumYunChaSeed.add(memberAccountDetailsViews.getSumYunChaSeed());
                        toBeYunChaSeed = toBeYunChaSeed.add(memberAccountDetailsViews.getToThawedYunChaSeed());
                    }
                    mothMemberNo = Integer.valueOf(mothMemberNo.intValue() + memberRepository.findByThisMonthMember(member1.getFUserId()));
                }
            }
            num += memberList.size();
            memberComprehensiveAnalysisView.setNum(Integer.valueOf(num));
            memberComprehensiveAnalysisView.setAdoptedOrderNum(Integer.valueOf(sum));
            memberComprehensiveAnalysisView.setMoney(money);
            memberComprehensiveAnalysisView.setMothMemberNo(mothMemberNo);
            memberComprehensiveAnalysisView.setWithdrawnAmount(withdrawnAmount);
            memberComprehensiveAnalysisView.setAmountToWithdrawn(AmountToWithdrawn);
            memberComprehensiveAnalysisView.setGiveTeaOilCard(giveTeaOilCard);
            memberComprehensiveAnalysisView.setToBeTeaOilCard(toBeTeaOilCard);
            memberComprehensiveAnalysisView.setHonBao(honBao);
            memberComprehensiveAnalysisView.setToBeConsumedHonBao(toBeConsumedHonBao);
            memberComprehensiveAnalysisView.setSumYunChaSeed(sumYunChaSeed);
            memberComprehensiveAnalysisView.setToBeYunChaSeed(toBeYunChaSeed);

            memberComprehensiveAnalysisView.setTodayAdoptedNo(toDayAdopted);
            memberComprehensiveAnalysisView.setTodayAdoptedMoney(toDayAdoptedMoney);
            memberComprehensiveAnalysisView.setThisMonthAdoptedNo(thisMonthAdopted);
            memberComprehensiveAnalysisView.setThisMonthAdoptedMoney(thisMonthAdoptedMoney);
            memberComprehensiveAnalysisView.setLastMonthAdoptedNo(lastAdopted);
            memberComprehensiveAnalysisView.setLastMonthAdoptedMoney(lastAdoptedMoney);
        }
        return Result.ok(memberComprehensiveAnalysisView);
    }
    public SimplePage<Map<String,Object>> findByMemberMobileStatistics(String mobile, Date startTime, Date endTime,
                                                                 Integer pageNum, Integer pageSize) {
        List<Map<String,Object>> performanceStatisticsView = memberRepository.findByMemberMobileStatistics(mobile,startTime,endTime,pageNum,pageSize);
        int total = memberRepository.getTotal();
        return new SimplePage<>(performanceStatisticsView, total);
    }
    public Result findByMemberMobileStatistics2(String mobile, Date startTime, Date endTime) {
        /*SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal=Calendar.getInstance();
        cal.add(Calendar.MONTH, -1);    //得到前一个月
        startTime = cal.getTime();
        endTime = new Date();*/
        List<Map<String,Object>> performanceStatisticsView = memberRepository.findByMemberMobileStatistics2(mobile,startTime,endTime);
        return Result.ok(performanceStatisticsView);
    }

    @Transactional(rollbackFor = {Exception.class})
    public void intervalThawYunChaSeed() {
        log.info("进来执行2023年定时解冻云茶籽了");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse("2024-01-01");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //查询资产类型为云茶籽("YUN_CHA_SEED"，即20240101之前认养的)且剩余量>0的用户。因为云茶籽剩余量>0才有得解冻
        List<Member> list = this.memberRepository.thawYunChaSeed();
        if (CollectionUtils.isNotEmpty(list)) {
            //2024年01月01日前认养的油茶树，自2024年01月01日开始，每棵树每天解冻6云茶籽（10棵就是60）,2024之前还是按照每棵树每天解冻3云茶籽
            //2024年01月01日及以后新认养的油茶树，每棵树每天还是解冻3云茶籽
            BigDecimal yunChaSeed = BigDecimal.ZERO;
            Optional<ValueConfig> valueConfig = valueConfigRepository.findById("system_thaw_yun_cha_seed_amount");
            if (valueConfig.isPresent() && StringUtils.isNotBlank(valueConfig.get().getValue())){
                yunChaSeed = new BigDecimal(valueConfig.get().getValue());
            }
            for (Member member : list) {
                //会员被冻结了不解冻云茶籽
                if ("FREEZE".equals(member.getMemberStatus())) {
                    continue;
                }
                //查询20240101之前，已经支付的认养树的总数量
                Integer adoptedTreeNum = this.adoptedTreeOrderRepository.findByUserIdAndBig(member.getFUserId(), date);
                log.info("2023年认养数量为:{}", adoptedTreeNum);
                //今天应该解冻的云茶籽
                BigDecimal yunChaSeedMoney = null;
                if (!Objects.isNull(adoptedTreeNum)){
                    yunChaSeedMoney = yunChaSeed.multiply(new BigDecimal(adoptedTreeNum.intValue()));
                }
                AssetCount assetCount = assetCountRepository.findByTypeAndUserId("YUN_CHA_SEED", member.getFUserId());
                if (null != assetCount) {
                    //判断一下剩余油茶籽是否够今天解冻的
                    if (assetCount.getRemainder().compareTo(yunChaSeedMoney) >= 0) {
                        //更新"云茶籽"资产，新增资产详情流水（如10棵树，解冻60个云茶籽，资产类型：云茶籽，交易类型：系统解冻云茶籽，交易金额：-60，意思是给你解冻60个了哈）。
                        Result<AssetDetail> result = this.assetCountService.saveRemainderAsset(member.getFUserId(), "YUN_CHA_SEED", "SYSTEM_THAW_YUN_CHA_SEED", yunChaSeedMoney
                                .negate(), member.getFUserId(), "", new Date());
                        if (0 == result.getCode()) {
                            //更新"RMB"资产，新增资产详情流水（如10棵树，解冻60个云茶籽，资产类型：人民币，交易类型：系统解冻云茶籽，交易金额：+60，意思是人民币资产增加了60个）。
                            this.assetCountService.saveRemainderAsset(member.getFUserId(), "RMB", "SYSTEM_THAW_YUN_CHA_SEED", yunChaSeedMoney, member
                                    .getFUserId(), "", new Date());
                        }
                        continue;
                    }
                    //如果剩余油茶籽不够今天解冻的，那就剩余多少解冻/释放多少
                    if (assetCount.getRemainder().compareTo(BigDecimal.ZERO) > 0) {
                        BigDecimal remainder = assetCount.getRemainder();
                        //更新"云茶籽"资产，新增资产详情流水
                        Result<AssetDetail> result = this.assetCountService.saveRemainderAsset(member.getFUserId(), "YUN_CHA_SEED", "SYSTEM_THAW_YUN_CHA_SEED", remainder
                                .negate(), null, "", new Date());
                        if (0 == result.getCode()) {
                            //更新"RMB"资产，新增资产详情流水
                            this.assetCountService.saveRemainderAsset(member.getFUserId(), "RMB", "SYSTEM_THAW_YUN_CHA_SEED", remainder, member
                                    .getFUserId(), "", new Date());
                        }
                    }
                }
            }
        }
    }
    @Transactional(rollbackFor = {Exception.class})
    public void intervalNewThawYunChaSeed() {
        log.info("进来执行2024年的解冻云茶籽");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = format.parse("2024-01-01");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //查询资产类型为云茶籽("NEW_YUN_CHA_SEED"，即20240101之后认养的)且剩余量>0的用户。因为云茶籽剩余量>0才有得解冻
        List<Member> list = this.memberRepository.thawNewYunChaSeed();
        if (CollectionUtils.isNotEmpty(list)) {
            //2024年01月01日前认养的油茶树，自2024年01月01日开始，每棵树每天解冻6云茶籽（10棵就是60）,2024之前还是按照每棵树每天解冻3云茶籽
            //2024年01月01日及以后新认养的油茶树，每棵树每天还是解冻3云茶籽
            BigDecimal yunChaSeed = BigDecimal.ZERO;
            Optional<ValueConfig> valueConfig = valueConfigRepository.findById("system_thaw_yun_cha_seed_amount_three");
            if (valueConfig.isPresent() && StringUtils.isNotBlank(valueConfig.get().getValue())){
                yunChaSeed = new BigDecimal(valueConfig.get().getValue());
            }
            for (Member member : list) {
                if ("FREEZE".equals(member.getMemberStatus())) {
                    continue;
                }
                Integer adoptedTreeNum = this.adoptedTreeOrderRepository.findByUserIdAndBig(member.getFUserId(), date);
                log.info("2024年认养的数量为:{}", adoptedTreeNum);
                //今天应该解冻的云茶籽
                BigDecimal yunChaSeedMoney = null;
                if (!Objects.isNull(adoptedTreeNum)){
                    yunChaSeedMoney = yunChaSeed.multiply(new BigDecimal(adoptedTreeNum.intValue()));
                }
                AssetCount assetCount = assetCountRepository.findByTypeAndUserId("NEW_YUN_CHA_SEED", member.getFUserId());
                //判断一下剩余油茶籽是否够今天解冻的
                if (null != assetCount) {
                    if (assetCount.getRemainder().compareTo(yunChaSeedMoney) >= 0) {
                        //更新"新云茶籽"资产，新增资产详情流水（如10棵树，解冻30个云茶籽，资产类型：新云茶籽，交易类型：系统解冻云茶籽，交易金额：-30，意思是给你解冻60个了哈）。
                        Result<AssetDetail> result = this.assetCountService.saveRemainderAsset(member.getFUserId(), "NEW_YUN_CHA_SEED","SYSTEM_THAW_YUN_CHA_SEED", yunChaSeedMoney
                                .negate(), member.getFUserId(), "", new Date());
                        if (0 == result.getCode()) {
                            //更新"RMB"资产，新增资产详情流水（如10棵树，解冻30个云茶籽，资产类型：人民币，交易类型：系统解冻云茶籽，交易金额：+30，意思是人民币资产增加了30个）。
                            this.assetCountService.saveRemainderAsset(member.getFUserId(), "RMB", "SYSTEM_THAW_YUN_CHA_SEED", yunChaSeedMoney, member
                                    .getFUserId(), "", new Date());
                        }
                        continue;
                    }
                    //如果剩余新油茶籽不够今天解冻的，那就剩余多少解冻/释放多少
                    if (assetCount.getRemainder().compareTo(BigDecimal.ZERO) > 0) {
                        BigDecimal remainder = assetCount.getRemainder();
                        //更新"新云茶籽"资产，新增资产详情流水
                        Result<AssetDetail> result = this.assetCountService.saveRemainderAsset(member.getFUserId(),"NEW_YUN_CHA_SEED","SYSTEM_THAW_YUN_CHA_SEED", remainder
                                .negate(), member.getFUserId(), "", new Date());
                        if (0 == result.getCode()) {
                            //更新"RMB"资产，新增资产详情流水
                            this.assetCountService.saveRemainderAsset(member.getFUserId(),"RMB", "SYSTEM_THAW_YUN_CHA_SEED", remainder, member
                                    .getFUserId(),"", new Date());
                        }
                    }
                }
            }
        }
    }

    @Transactional(rollbackFor = {Exception.class})
    public void intervalThawConsumerGoldRedEnvelope() {
        log.info("定时解冻消费金红包");
        //查询资产类型为消费金红包("CONSUMER_GOLD_RED_ENVELOPE")且剩余量>0的用户。因为消费金红包剩余量>0才有得解冻
        List<Member> list = this.memberRepository.thawConsumerGoldRedEnvelope();
        if (CollectionUtils.isNotEmpty(list)) {
            //获取配置的系统每天解冻消费金红包数量
            BigDecimal consumerGoldRedEnvelope = BigDecimal.ZERO;
            Optional<ValueConfig> valueConfig = valueConfigRepository.findById("system_thaw_consumer_gold_red_envelope");
            if (valueConfig.isPresent() && StringUtils.isNotBlank(valueConfig.get().getValue())){
                consumerGoldRedEnvelope = new BigDecimal(valueConfig.get().getValue());
            }
            for (Member member : list) {
                if ("FREEZE".equals(member.getMemberStatus())) {
                    continue;
                }
                //认养树总数量
                Integer adoptedTreeNum = this.adoptedTreeOrderRepository.findByUserId(member.getFUserId());
                //今天应该解冻的消费金红包。认养树数量x3
                BigDecimal sumMoney = consumerGoldRedEnvelope.multiply(new BigDecimal(adoptedTreeNum.intValue()));
                //如果超过1500，则按照1500进行解冻
                if (sumMoney.compareTo(new BigDecimal(1500)) >= 0) {
                    sumMoney = new BigDecimal(1500);
                }
                AssetCount assetCount = assetCountRepository.findByTypeAndUserId("YUN_CHA_SEED", member.getFUserId());
                //判断一下剩余油茶籽是否够今天解冻的
                if (assetCount.getRemainder().compareTo(sumMoney) >= 0) {
                    //更新"消费金红包"资产，新增资产详情流水（如10棵树，解冻30个消费金红包，资产类型：消费金红包，交易类型：系统自动领取，交易金额：-30，意思是给你解冻30个了哈）。
                    Result<AssetDetail> result = this.assetCountService.saveRemainderAsset(member.getFUserId(),"CONSUMER_GOLD_RED_ENVELOPE","SYSTEM_THAW_CONSUMER_GOLD_RED_ENVELOPE", sumMoney
                            .negate(), null,"", new Date());
                    if (0 == result.getCode()) {
                        //更新"解冻消费金红包"资产，新增资产详情流水（如10棵树，解冻30个消费金红包，资产类型：解冻消费金红包，交易类型：系统自动领取，交易金额：+30，意思是人民币资产增加了30个）。
                        this.assetCountService.saveRemainderAsset(member.getFUserId(),"UNFREEZING_CONSUMER_GOLD_RED_ENVELOPE","SYSTEM_THAW_CONSUMER_GOLD_RED_ENVELOPE", sumMoney, null,"", new Date());
                    }
                    continue;
                }
                if (assetCount.getRemainder().compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal remainder = assetCount.getRemainder();
                    //更新"消费金红包"资产，新增资产详情流水
                    Result<AssetDetail> result = this.assetCountService.saveRemainderAsset(member.getFUserId(),"CONSUMER_GOLD_RED_ENVELOPE","SYSTEM_THAW_CONSUMER_GOLD_RED_ENVELOPE", remainder
                            .negate(), null,"", new Date());
                    if (0 == result.getCode()) {
                        //更新"解冻消费金红包"资产，新增资产详情流水
                        this.assetCountService.saveRemainderAsset(member.getFUserId(),"UNFREEZING_CONSUMER_GOLD_RED_ENVELOPE","SYSTEM_THAW_CONSUMER_GOLD_RED_ENVELOPE", remainder, null,"", new Date());
                    }
                }
            }
        }
    }

    @Transactional(rollbackFor = {Exception.class})
    public Result saveWeixinUserExtend(WeixinUser weixinUser) {
        log.info("初始化信息为:{}", weixinUser);
        Member member = this.memberRepository.findByUserId(weixinUser.getUserId());
        if (member != null) {
            return Result.ok();
        }
        member = new Member();
        member.setFUserId(weixinUser.getUserId());
        if (StringUtils.isNotBlank(weixinUser.getParentCode())) {
            Member parent = this.memberRepository.findByCode(weixinUser.getParentCode());
            if (parent != null) {
                member.setParentCode(parent.getCode());
            }
        }
        log.info("777:{}", weixinUser);
        member.setGender(Integer.valueOf(0));
        member.setLevel("COMMON");
        member.setCode(weixinUser.getPhoneNumber());
        member.setMobile(weixinUser.getPhoneNumber());
        member.setMemberStatus("NORMAL");
        member.setRoleTwo("NO");
        member.setRole("NO");
        if (StringUtils.isBlank(weixinUser.getPhoneNumber())) {
            member.setNickname(String.format("芯禾%s", new Object[] { CharCodeUtil.generateCharRandomCode(8) }));
        } else {
            member.setNickname(weixinUser.getPhoneNumber().replaceAll("(\\d{3})\\d{6}(\\d{2})", "$1******$2"));
        }
        member.setIconPath("https://xhyp.quexiaoer.cn/upload/default/default_avatar.png");
        this.memberRepository.save(member);
        this.assetCountService.initAssetCount(member.getFUserId());
        log.info("完成:{}", weixinUser);
        return Result.ok();
    }
    public Result findByUserCount() {
        List<Member> memberList = this.memberRepository.findAll();
        Integer toDayMember = this.memberRepository.findByTodayMember();
        Integer yesterdayMember = this.memberRepository.findByYesterday();
        Integer thisMonthMember = this.memberRepository.findByThisMonthMember(null);
        Integer sumAdopted = this.adoptedTreeOrderRepository.findByCompanySum();
        Integer toDayAdopted = this.adoptedTreeOrderRepository.findByToDayAdopted();
        Integer yesterdayAdopted = this.adoptedTreeOrderRepository.findByYesterdayAdopted();
        Integer thisMonthAdopted = this.adoptedTreeOrderRepository.findByThisMonthAdopted();
        BigDecimal totalMoney = this.adoptedTreeOrderRepository.findByTotalMoney();
        BigDecimal toDayAdoptedMoney = this.adoptedTreeOrderRepository.findByToDayAdoptedMoney();
        BigDecimal yesterdayAdoptedMoney = this.adoptedTreeOrderRepository.findByYesterdayAdoptedMoney();
        BigDecimal thisMonthAdoptedMoney = this.adoptedTreeOrderRepository.findByThisMonthAdoptedMoney();
        Integer payMember = this.memberRepository.findByPayAndNoPay0(0);
        Integer noPayMember = this.memberRepository.findByPayAndNoPay1(1);
        Map<String, Object> map = new HashMap<>();
        map.put("totalMember", Integer.valueOf(memberList.size()));
        map.put("toDayMember", toDayMember);
        map.put("yesterdayMember", yesterdayMember);
        map.put("thisMonthMember", thisMonthMember);
        map.put("sumAdopted", sumAdopted);
        map.put("toDayAdopted", toDayAdopted);
        map.put("yesterdayAdopted", yesterdayAdopted);
        map.put("thisMonthAdopted", thisMonthAdopted);
        map.put("totalMoney", totalMoney);
        map.put("toDayAdoptedMoney", toDayAdoptedMoney);
        map.put("yesterdayAdoptedMoney", yesterdayAdoptedMoney);
        map.put("thisMonthAdoptedMoney", thisMonthAdoptedMoney);
        map.put("payMember", payMember);
        map.put("noPayMember", noPayMember);
        return Result.ok(map);
    }
    public Result findByMoonDays() {
        List<MemberPlatformMothView> memberCountList = new ArrayList<>();
        List<MemberPlatformMothView> OrderCountList = new ArrayList<>();
        List<MemberPlatformMothView> OrderPayCountList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<String> times = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            Calendar instance = Calendar.getInstance();
            instance.add(5, -i);
            String date = format.format(instance.getTime());
            times.add(date);
        }
        times.sort(String::compareTo);
        map.put("times", times);
        //先查询返回map，再转为List<MemberPlatformMothView>，因为jpa原生sql不支持直接返回List<MemberPlatformMothView>
        List<Map<String,String>> mapList = this.memberRepository.findByBranchDataStatistics();
        List<MemberPlatformMothView> shopReplenishmentView = null;
        if (CollectionUtils.isEmpty(mapList)) {
            shopReplenishmentView = new ArrayList<>();
        }else {
            for (Map<String, String> map1 : mapList) {
                MemberPlatformMothView member = new MemberPlatformMothView();
                member.setTime(map1.get("time"));
                member.setAmount(map1.get("amount"));
                shopReplenishmentView.add(member);
            }
        }
        Map<String, MemberPlatformMothView> memberMoth = (Map<String, MemberPlatformMothView>)shopReplenishmentView.stream().collect(Collectors.toMap(MemberPlatformMothView::getTime, shopReplenishmentView1 -> shopReplenishmentView1));
        List<MemberPlatformMothView> orderMothCount = null;
        //先查询返回map，再转为List，因为jpa原生sql不支持直接返回List<MemberPlatformMothView>
        List<Map<String,String>> mapList2 = this.adoptedTreeOrderRepository.findByMothCount();
        if (CollectionUtils.isEmpty(mapList2)) {
            orderMothCount = new ArrayList<>();
        }else {
            for (Map<String, String> map2 : mapList2) {
                MemberPlatformMothView member = new MemberPlatformMothView();
                member.setTime(map2.get("time"));
                member.setAmount(map2.get("amount"));
                orderMothCount.add(member);
            }
        }
        Map<String, MemberPlatformMothView> orderMoth = (Map<String, MemberPlatformMothView>)orderMothCount.stream().collect(Collectors.toMap(MemberPlatformMothView::getTime, shopReplenishmentView1 -> shopReplenishmentView1));
        List<MemberPlatformMothView> orderPayMothCount = null;
        //先查询返回map，再转为List，因为jpa原生sql不支持直接返回List<MemberPlatformMothView>
        List<Map<String,String>> mapList3 = this.adoptedTreeOrderRepository.findByOrderPayMothCount();
        if (CollectionUtils.isEmpty(mapList3)) {
            orderPayMothCount = new ArrayList<>();
        }else {
            for (Map<String, String> map3 : mapList3) {
                MemberPlatformMothView member = new MemberPlatformMothView();
                member.setTime(map3.get("time"));
                member.setAmount(map3.get("amount"));
                orderPayMothCount.add(member);
            }
        }
        Map<String,MemberPlatformMothView> orderPayMoth = (Map<String, MemberPlatformMothView>)orderPayMothCount.stream().collect(Collectors.toMap(MemberPlatformMothView::getTime, shopReplenishmentView1 -> shopReplenishmentView1));
        for (String time : times) {
            MemberPlatformMothView shopReplenishment = memberMoth.get(time);
            if (shopReplenishment == null) {
                shopReplenishment = new MemberPlatformMothView(time, "0");
            }
            memberCountList.add(new MemberPlatformMothView(time, shopReplenishment.getAmount()));
            MemberPlatformMothView shopMeltOrder = orderMoth.get(time);
            if (shopMeltOrder == null) {
                shopMeltOrder = new MemberPlatformMothView(time, "0");
            }
            OrderCountList.add(new MemberPlatformMothView(time, shopMeltOrder.getAmount()));
            MemberPlatformMothView OrderPayMelt = orderPayMoth.get(time);
            if (OrderPayMelt == null) {
                OrderPayMelt = new MemberPlatformMothView(time, "0");
            }
            OrderPayCountList.add(new MemberPlatformMothView(time, OrderPayMelt.getAmount()));
        }
        List<List<MemberPlatformMothView>> views = new ArrayList<>();
        views.add(memberCountList);
        views.add(OrderCountList);
        views.add(OrderPayCountList);
        return Result.ok(views);
    }
    public Result pageMemberConsumptionRanking(MemberQuery query) {
        List<Member> memberList = this.memberRepository.findAll();
        List<MemberTopTenView> list = new ArrayList<>();
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        //并发处理会员列表中的每个会员对象，并计算每个会员对象的费用，并将结果保存到一个列表中。代码使用了CompletableFuture来实现异步并发处理。
        //使用CompletableFuture.runAsync方法来实现并行处理，并使用CompletableFuture.allOf方法等待所有处理完成。这种方式可以有效地利用多线程处理并发任务，提高代码的性能。
        //递归方法(recursion)来计算会员对象的费用，将结果保存到结果列表(list)中
        for (Iterator<Member> iterator = memberList.iterator(); iterator.hasNext(); ) {
            Member member = iterator.next();
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                BigDecimal sum = recursion(member, BigDecimal.ZERO, query, futures);
                System.out.println("费用：" + sum);
                list.add(new MemberTopTenView(member.getName(), sum, member.getFUserId()));
            },ThreadPoolUtil.THREAD_POOL_EXECUTOR);
            futures.add(future);
        }
        try {
            /*
            CompletableFuture的allOf方法等待所有的CompletableFuture都完成。通过调用get方法来获取等待结果，可以防止线程继续执行，并处理任何潜在的InterruptedException和ExecutionException异常。
            CompletableFuture.allOf方法会阻塞，直到所有的CompletableFuture都完成。如果其中一个CompletableFuture还没有完成，这行代码会一直等待，直到所有的CompletableFuture都完成或者抛出异常。
            在这行代码中，它将所有的CompletableFuture都转换为一个数组，然后通过toArray方法将其转换为CompletableFuture[]。接着调用CompletableFuture.allOf方法，它接受一个CompletableFuture[]作为参数，并返回一个新的CompletableFuture，这个新的CompletableFuture在所有传入的CompletableFuture都完成后完成。
            .get()方法则会等待CompletableFuture.allOf返回的CompletableFuture完成，即等待所有传入的CompletableFuture都完成。如果有任何一个CompletableFuture抛出了异常，那么.get()方法也将抛出异常。
            所以，在多线程任务中，如果有一个或多个CompletableFuture没有完成，这行代码会阻塞等待它们的完成。只有当所有的CompletableFuture都完成后，阻塞才会解除。

            toArray方法有两个重载版本：
            Object[] toArray()：将集合转换为Object数组。
            <T> T[] toArray(T[] a)：将集合转换为指定类型的数组。
            在这里，futures是一个List<CompletableFuture<Void>>类型列表，通过调用toArray方法将其转换为CompletableFuture[]类型的数组。由于无法直接将泛型参数转换为数组类型，所以需要将参数传递为一个空数组，这里通过new CompletableFuture[0]创建了一个空的CompletableFuture数组作为参数。这样就能够取得一个CompletableFuture[]类型的数组，可以传递给CompletableFuture.allOf方法进行处理。
            */
            CompletableFuture.allOf((CompletableFuture<?>[])futures.<CompletableFuture>toArray(new CompletableFuture[0])).get();
        } catch (InterruptedException|java.util.concurrent.ExecutionException e) {
            e.printStackTrace();
        }
        List<MemberTopTenView> dataList = (List<MemberTopTenView>)list.stream().sorted(Comparator.comparing(MemberTopTenView::getMoney).reversed()).limit(10L).collect(Collectors.toList());
        for (MemberTopTenView memberTopTenView : dataList) {
            System.out.println("前10数据：" + JSONArray.toJSONString(memberTopTenView));
        }
        return Result.ok(dataList);
    }
    private BigDecimal recursion(Member parent, BigDecimal fee, MemberQuery query, List<CompletableFuture<Void>> futures) {
        BigDecimal[] money1 = { fee };
        List<Member> members = this.memberRepository.findBySubordinateCode(parent.getCode());
        if (CollectionUtils.isNotEmpty(members)) {
            for (Member member1 : members) {
                query.setUserId(member1.getFUserId());
                BigDecimal money = new BigDecimal(0);
                if (StringUtils.isNotBlank(query.getDateType())){
                    if ("TODAY".equals(query.getDateType())) {
                        money = this.adoptedTreeOrderRepository.findUserIdAndAdoptedTReeMoney1(query.getUserId());
                    }else if ("YESTERDAY".equals(query.getDateType())) {
                        money = this.adoptedTreeOrderRepository.findUserIdAndAdoptedTReeMoney2(query.getUserId());
                    }else if ("LAST_MONTH".equals(query.getDateType())) {
                        money = this.adoptedTreeOrderRepository.findUserIdAndAdoptedTReeMoney3(query.getUserId());
                    }else {
                        money = this.adoptedTreeOrderRepository.findUserIdAndAdoptedTReeMoney4(query.getUserId());
                    }
                }else {
                    money = this.adoptedTreeOrderRepository.findUserIdAndAdoptedTReeMoney5(query.getUserId());
                }
                money1[0] = money1[0].add(money);
                money1[0] = money1[0].add(recursion(member1, BigDecimal.ZERO, query, futures));
            }
        }
        return money1[0];
    }
    public Result pageMemberWithdrawal(MemberQuery query) {
        QMember qMember = QMember.member;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qMember.removed.eq(0));
        List<MemberTopTenView> memberTopTenViewList = queryFactory.select(
                Projections.bean(
                        MemberTopTenView.class,
                        qMember.name,
                        qMember.id
                )
        ).from(qMember).where(builder).limit(10).fetch();
        //对结果进行修改
        for (MemberTopTenView memberTopTenView : memberTopTenViewList){
            BigDecimal money = new BigDecimal(0);
            if (StringUtils.isNotBlank(query.getDateType())){
                if ("TODAY".equals(query.getDateType())) {
                    money = this.withdrawalsRecordRepository.findMoney1(memberTopTenView.getUserId());
                }else if ("YESTERDAY".equals(query.getDateType())) {
                    money = this.withdrawalsRecordRepository.findMoney2(memberTopTenView.getUserId());
                }else{
                    money = this.withdrawalsRecordRepository.findMoney3(memberTopTenView.getUserId());
                }
            }else {
                money = this.withdrawalsRecordRepository.findMoney4(memberTopTenView.getUserId());
            }
            memberTopTenView.setMoney(money);
        }
        //对结果按照money倒叙排列,使用Comparator接口和Collections.sort方法按照金额money降序排列
        Collections.sort(memberTopTenViewList, Comparator.comparing(MemberTopTenView::getMoney).reversed());
        return Result.ok(memberTopTenViewList);
    }
    public Result findByFounderConsumptionRanking(MemberQuery query) {
        List<Member> memberList = new ArrayList<>();
        if (null != query.getServiceId()){
            memberList = this.memberRepository.findFounderMember1();
        }else {
            memberList = this.memberRepository.findFounderMember2(query.getServiceId());
        }
        List<MemberTopTenView> list = new ArrayList<>();
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (Iterator<Member> iterator = memberList.iterator(); iterator.hasNext();){
            Member member = iterator.next();
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                BigDecimal sum = recursion(member, BigDecimal.ZERO, query, futures);
                System.out.println("费用：" + sum);
                list.add(new MemberTopTenView(member.getName(), sum, member.getFUserId()));
            },ThreadPoolUtil.THREAD_POOL_EXECUTOR);
            futures.add(future); }
        try {
            CompletableFuture.allOf((CompletableFuture<?>[])futures.<CompletableFuture>toArray(new CompletableFuture[0])).get();
        } catch (InterruptedException|java.util.concurrent.ExecutionException e) {
            e.printStackTrace();
        }
        List<MemberTopTenView> dataList = (List<MemberTopTenView>)list.stream().sorted(Comparator.comparing(MemberTopTenView::getMoney).reversed()).limit(10L).collect(Collectors.toList());
        for (MemberTopTenView memberTopTenView : dataList) {
            System.out.println("前10数据：" + JSONArray.toJSONString(memberTopTenView));
        }
        return Result.ok(dataList);
    }
    public Result findByFounderWithdrawal(MemberQuery query) {
        QMember qMember = QMember.member;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qMember.removed.eq(0));
        builder.and(qMember.role.eq("FOUNDER"));
        List<MemberTopTenView> memberTopTenViewList = queryFactory.select(
                Projections.bean(
                        MemberTopTenView.class,
                        qMember.name,
                        qMember.id
                )
        ).from(qMember).where(builder).limit(10).fetch();
        //对结果进行修改
        for (MemberTopTenView memberTopTenView : memberTopTenViewList){
            BigDecimal money = new BigDecimal(0);
            if (StringUtils.isNotBlank(query.getDateType())){
                if ("TODAY".equals(query.getDateType())) {
                    money = this.withdrawalsRecordRepository.findMoney7(memberTopTenView.getUserId());
                }else if ("YESTERDAY".equals(query.getDateType())) {
                    money = this.withdrawalsRecordRepository.findMoney8(memberTopTenView.getUserId());
                }else{
                    money = this.withdrawalsRecordRepository.findMoney9(memberTopTenView.getUserId());
                }
            }else {
                money = this.withdrawalsRecordRepository.findMoney10(memberTopTenView.getUserId());
            }
            memberTopTenView.setMoney(money);
        }
        //对结果按照money倒叙排列,使用Comparator接口和Collections.sort方法按照金额money降序排列
        Collections.sort(memberTopTenViewList, Comparator.comparing(MemberTopTenView::getMoney).reversed());
        return Result.ok(memberTopTenViewList);
    }
    public Result easyMemberAccountDetailExcel(MemberQuery query) {
        /*query.setLimit(Integer.valueOf(-1));
        List<MemberAccountDetailsView> memberAccountDetailsViews = this.memberDao.pageMemberAccountDetail(query);
        if (CollectionUtils.isEmpty(memberAccountDetailsViews)) {
            throw new BusinessException("你没有可以导出的数据");
        }
        List<MemberAccountDetailEasyView> easyViews = new ArrayList<>();

        for (MemberAccountDetailsView view : memberAccountDetailsViews) {
            MemberAccountDetailEasyView accountDetailEasyView = new MemberAccountDetailEasyView();
            accountDetailEasyView.setMobile(view.getMobile());
            accountDetailEasyView.setName(view.getName());
            accountDetailEasyView.setAdoptionNum(view.getAdoptionNum());
            accountDetailEasyView.setRmb(view.getRmb());
            accountDetailEasyView.setToThawedYunChaSeed(view.getToThawedYunChaSeed());
            accountDetailEasyView.setThawedYunChaSeed(view.getThawedTunChaSeed());
            accountDetailEasyView.setSumYunChaSeed(view.getSumYunChaSeed());
            accountDetailEasyView.setTeaOilCard(view.getTeaOilCard());
            accountDetailEasyView.setSumTeaOilCard(view.getSumTeaOilCard());
            accountDetailEasyView.setToThawedConsumerGoldRedEnvelope(view.getToThawedConsumerGoldRedEnvelope());
            accountDetailEasyView.setThawedConsumerGoldRedEnvelope(view.getThawedConsumerGoldRedEnvelope());
            accountDetailEasyView.setSumConsumerGoldRedEnvelope(view.getSumConsumerGoldRedEnvelope());
            easyViews.add(accountDetailEasyView);
        }
        String name = "会员账户明细记录";
        File file = createFile(name);
        System.out.println("导出的值为：" + easyViews);
        if (CollectionUtils.isNotEmpty(easyViews)) {
            ((ExcelWriterSheetBuilder)EasyExcel.write(file).sheet("会员账户明细记录")
                    .head(MemberAccountDetailEasyView.class))
                    .doWrite(easyViews);
            result.setItem("/temp/" + file.getName());
            System.out.println("导出的路径名称为:" + file.getName());
        }
        System.out.println("导出的路径名称为:" + file.getName());*/
        return Result.ok();
    }

    @Transactional
    public Result memberLogInNow(String mobile, String password, String wxCode) {
        if (StringUtils.isEmpty(mobile)) {
            throw new BusinessException(1001,"手机号不能为空");
        }
        if (StringUtils.isEmpty(password)) {
            throw new BusinessException(1002,"密码不能为空");
        }
        String pwd = DigestUtils.md5Hex(password);
        Member member = this.memberRepository.findByMobileAndPassword(mobile, pwd);
        if (member == null) {
            throw new BusinessException(1003,"手机号或密码错误");
        }
        if (StringUtils.isNotBlank(wxCode)) {
            //调用微信小程序接口获取openid
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", new Object[] {appid,appsecret, wxCode}));
            try {
                CloseableHttpResponse response = httpClient.execute((HttpUriRequest)httpGet);
                Throwable var8 = null;
                try {
                    HttpEntity body = response.getEntity();
                    String respJson = EntityUtils.toString(body, "UTF-8");
                    JSONObject tokenJsonObj = JSONObject.parseObject(respJson);
                    String openId = tokenJsonObj.getString("openid");
                    String unionId = tokenJsonObj.getString("unionid");
                    System.out.println("openid为：" + openId);
                    WeixinUser weixinUser = this.weixinUserRepository.findOneByConfigIdAndUserId(519802482830868480L,member.getFUserId());
                    if (weixinUser == null) {
                        weixinUser = new WeixinUser();
                        weixinUser.setOpenid(openId);
                        weixinUser.setConfigId(519802482830868480L);//代表小程序用户
                        weixinUser.setPhoneNumber(mobile);
                        weixinUser.setUserId(member.getFUserId());
                        weixinUser.setUnionid(unionId);
                        this.weixinUserRepository.save(weixinUser);
                    } else {
                        weixinUser.setUnionid(unionId);//同一个用户，在你的多个应用中，openid可能都不相同；但是，unionid一定会相同的。
                        this.weixinUserRepository.saveAndFlush(weixinUser);
                    }
                } catch (Throwable var25) {
                    var8 = var25;
                    throw var25;
                } finally {
                    if (response != null) {
                        if (var8 != null) {
                            try {
                                response.close();
                            } catch (Throwable var24) {
                                var8.addSuppressed(var24);
                            }
                        } else {
                            response.close();
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new BusinessException(1004,e.getMessage());
            }
        }
        Map<String, Object> map = new HashMap<>();
        Set<Long> roleIds = new HashSet<>();
        Result userSessionViewResult = this.userService.userLogin(member.getFUserId(),roleIds,null);
        map.put("token", ((UserSessionView)userSessionViewResult.getData()).getToken());
        return Result.ok(map);
    }
    public Result findByMember() {
        Long userId = this.userSessionManager.getUserId();
        QMember qMember = QMember.member;
        QServiceCenter qServiceCenter = QServiceCenter.serviceCenter; ;
        QIdentity qIdentity = QIdentity.identity;
        BooleanBuilder builder = new BooleanBuilder();
        OrderSpecifier<Date> sort = qMember.createTime.desc();
        builder.and(qMember.removed.eq(0));
        builder.and(qMember.fUserId.eq(userId));
        MemberView memberView = queryFactory.select(
                Projections.bean(
                        MemberView.class,
                        qMember.name,
                        qMember.nickname,
                        qMember.iconPath,
                        qMember.id,
                        qMember.fUserId,
                        qMember.mobile,
                        qMember.code,
                        qMember.parentCode,
                        qMember.gender,
                        qMember.level,
                        qMember.remark,
                        qMember.createTime,
                        qMember.role,
                        qMember.adoptionDate,
                        qMember.adoptionNum,
                        qMember.newReference,
                        qMember.roleTwo,
                        qMember.threeThawAdopted,
                        qMember.identifying,
                        qMember.twoThawAdopted,
                        qMember.threeThawNo,
                        qMember.memberStatus,
                        qMember.memberStatus,
                        qServiceCenter.name.as("serviceName"),
                        qIdentity.checkStatus
                )
        ).from(qMember)
                .leftJoin(qServiceCenter).on(qMember.fServiceId.eq(qServiceCenter.id))
                .leftJoin(qIdentity).on(qMember.fUserId.eq(qIdentity.fUserId).and(qIdentity.checkStatus.eq("SUCCESS")))
                .where(builder).fetchOne();
        String parentName = memberRepository.queryParentName(memberView.getParentCode());
        String parentMobile= memberRepository.queryParentMobile(memberView.getParentCode());
        memberView.setParentMobile(parentMobile);
        memberView.setParentName(parentName);
        return Result.ok(memberView);
    }
    public Result findByMemberPhone() {
        Member member = this.memberRepository.findByUserId(this.userSessionManager.getUserId());
        if (null == member) {
            return Result.ok();
        } else {
            return Result.ok(member.getMobile());
        }
    }
    public Result findByDirectPushAndInterpenetration() {
        Long userId = this.userSessionManager.getUserId();
        //userId = 604183377410523136L;
        //间接推荐数量：我所有推荐人的下级推荐的人数总和，即间接推荐人数。
        Map<String, Integer> res = this.memberRepository.findByDirectPushAndInterpenetration(userId);
        return Result.ok(res);
    }
    public Result findByMemberDirectPush() {
        List<Map<String, Object>> filteredListMap = new ArrayList<>();
        Long userId = this.userSessionManager.getUserId();
        Member member = this.memberRepository.findByUserId(userId);
        List<Map<String, Object>> listmap = this.memberRepository.findByParentCode(member.getFUserId());
        if (CollectionUtils.isNotEmpty(listmap)) {
            // 去除userid值为null的记录
            for (Map<String, Object> map : listmap) {
                if (map.get("userid") != null) {
                    filteredListMap.add(map);
                }
            }
        }
        return Result.ok(filteredListMap);
    }

    public Result findByMemberInterpenetration() {
        Long userId = this.userSessionManager.getUserId();
        Member member = this.memberRepository.findByUserId(userId);
        List<Map<String, Object>> listmap = this.memberRepository.findByInterpenetration(member.getFUserId());
        return Result.ok(listmap);
    }
    public Result findByNotCommonMember(MemberQuery query) {
        QMember qMember = QMember.member;
        BooleanBuilder builder = new BooleanBuilder();
        OrderSpecifier<Date> sort = qMember.createTime.desc();
        builder.and(qMember.removed.eq(0));
        List<String> roleList = new ArrayList<>();
        roleList.add("FOUNDER");
        roleList.add("SMART_PARTNER");
        builder.and(qMember.level.eq("HOME_ANGEL").or(qMember.role.in(roleList)));
        if (StringUtils.isNotBlank(query.getKeyword())) {
            builder.and(qMember.nickname.like(query.getKeyword()).or(qMember.name.like(query.getKeyword())).or(qMember.mobile.like(query.getKeyword())));
        }
        List<Member> memberList = queryFactory.select(
                Projections.bean(
                        Member.class,
                        qMember.name,
                        qMember.removed,
                        qMember.memberStatus,
                        qMember.id,
                        qMember.createTime,
                        qMember.remark,
                        qMember.versionNum,
                        qMember.fServiceId,
                        qMember.fUserId,
                        qMember.iconPath,
                        qMember.nickname,
                        qMember.mobile,
                        qMember.code,
                        qMember.parentCode,
                        qMember.gender,
                        qMember.level,
                        qMember.role,
                        qMember.roleTwo,
                        qMember.adoptionDate,
                        qMember.adoptionNum,
                        qMember.newReference,
                        qMember.identifying,
                        qMember.twoThawNo,
                        qMember.threeThawNo,
                        qMember.twoThawAdopted,
                        qMember.threeThawAdopted,
                        qMember.isImportMember,
                        qMember.disengageNo
                )
        ).from(qMember)
                .where(builder).fetch();
        return Result.ok(memberList);
    }
    @Transactional
    public Result redeemNowTeaOilCard(Integer number) {
        Long userId = this.userSessionManager.getUserId();
        AssetCount assetCount = this.assetCountService.findByTypeAndUserId("TEA_OIL_CARD", userId).getData();
        if (assetCount.getRemainder().compareTo(new BigDecimal(number.intValue())) < 0) {
            throw new BusinessException(1001,"兑换数量超出已有数量");
        }
        this.assetCountService.saveRemainderAsset(userId, "TEA_OIL_CARD","ADOPTED_OIL_CARD_EXCHANGE_TEA_OIL", (new BigDecimal(number
                .intValue())).negate(), userId,"",new Date());
        this.assetCountService.saveRemainderAsset(userId,"TEA_OIL","ADOPTED_OIL_CARD_EXCHANGE_TEA_OIL", new BigDecimal(number
                .intValue()), userId,"",new Date());
        return Result.ok();
    }

    public Result findByMobile(String code) {
        String urls = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", new Object[] {appid, appsecret});
        HttpEntity entity = HttpClientUtil.requestGet(urls);
        assert entity != null;
        String m = null;
        try {
            if (entity != null) {
                m = EntityUtils.toString(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(m);
        JSONObject jsonObject = JSONObject.parseObject(m);
        String access_token = jsonObject.getString("access_token");
        if (StringUtils.isNotEmpty(access_token)) {
            String url = String.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s", new Object[] { access_token });
            Map<String, Object> maps = new HashMap<>();
            maps.put("code", code);
            JSONObject jsonObject1 = HttpClientUtil.requestJsonPost(url, maps, new HashMap<>());
            String errmsg = jsonObject1.getString("errmsg");
            if ("ok".equals(errmsg)) {
                JSONObject phone_info = jsonObject1.getJSONObject("phone_info");
                String phoneNumber = phone_info.getString("phoneNumber");
                return Result.ok(phoneNumber);
            } else {
                return Result.failed(102,errmsg);
            }
        }
        return Result.ok();
    }
    @Transactional
    public Result updatePassword(String mobile,String code,String password,String confirmPassword) {
        String i = "^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\\d{8}$";
        Pattern compile = Pattern.compile(i);
        if (!compile.matcher(mobile).matches()) {
            throw new BusinessException(101,"手机格式不正确");
        }
        if (null == code) {
            throw new BusinessException(102,"验证码不能为空");
        }
        Result result = this.aliyunService.validCode(mobile,code);
        if (0!=result.getCode()) {
            throw new BusinessException(103,"验证码错误");
        }
        Member member = this.memberRepository.findByMobile(mobile);
        if (null == member) {
            throw new BusinessException(104,"用户不存在");
        }
        if (!password.equals(confirmPassword)) {
            throw new BusinessException(105,"俩次密码不一致,请重新输入");
        }
        member.setPassword(DigestUtils.md5Hex(password));
        this.memberRepository.saveAndFlush(member);
        return Result.ok();
    }
    @Transactional
    public Result memberRegisterNow(String iconPath,String name,String mobile,String code,String wxCode,String parentCode) {
        String i = "^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\\d{8}$";
        Pattern compile = Pattern.compile(i);
        if (!compile.matcher(mobile).matches()) {
            throw new BusinessException(100,"手机格式不正确");
        }
        if (null == code) {
            throw new BusinessException(101,"验证码不能为空");
        }
        Result result = this.aliyunService.validCode(mobile,code);
        if (0!=result.getCode()) {
            throw new BusinessException(102,"验证码错误");
        }
        if (StringUtils.isNotBlank(parentCode)) {
            Member byCode = this.memberRepository.findMemberByCode(parentCode);
            if (null == byCode) {
                throw new BusinessException(103,"推荐人不存在");
            }
            if ("COMMON".equals(byCode.getLevel())) {
                throw new BusinessException(104,"推荐人没有推荐权限");
            }
        }
        Map<String, Object> map = new HashMap<>();
        Member member = this.memberRepository.findByMobile(mobile);
        if (null == member) {
            //role_id_weixin_mini_program 平台会员角色ID=213183559102365696
            Result userResult = this.userService.registerUser(new UserRegisterModel(mobile, null, null, new Long[] { 213183559102365696L }));
            member = new Member();
            member.setFUserId((Long.valueOf((String) userResult.getData())));
            if (StringUtils.isNotBlank(parentCode)) {
                Member parent = this.memberRepository.findByCode(parentCode);
                if (parent != null) {
                    member.setFServiceId(parent.getFServiceId());
                    member.setParentCode(parent.getCode());
                    member.setNewReference(parent.getCode());
                }
            }
            member.setGender(Integer.valueOf(0));
            member.setLevel("COMMON");
            member.setRoleTwo("NO");
            member.setRole("NO");
            member.setMemberStatus("NORMAL");
            member.setCode(mobile);
            member.setIsImportMember(Integer.valueOf(1));
            member.setMobile(mobile);
            member.setName(name);
            member.setPassword(DigestUtils.md5Hex("123456"));
            member.setNickname(mobile.replaceAll("(\\d{3})\\d{6}(\\d{2})", "$1******$2"));
            member.setIconPath("https://xhyp.quexiaoer.cn/upload/default/default_avatar.png");
            this.memberRepository.save(member);
            this.assetCountService.initAssetCount(member.getFUserId());
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", new Object[] {appid,appsecret,wxCode }));
            try {
                CloseableHttpResponse response = httpClient.execute((HttpUriRequest)httpGet);
                Throwable var8 = null;
                try {
                    HttpEntity body = response.getEntity();
                    String respJson = EntityUtils.toString(body, "UTF-8");
                    JSONObject tokenJsonObj = JSONObject.parseObject(respJson);
                    String openId = tokenJsonObj.getString("openid");
                    String unionId = tokenJsonObj.getString("unionid");
                    WeixinUser weixinUser = this.weixinUserRepository.findOneByOpenid(openId);
                    if (weixinUser == null) {
                        weixinUser = new WeixinUser();
                        weixinUser.setOpenid(openId);
                        weixinUser.setConfigId(519802482830868480L);
                        weixinUser.setParentCode(parentCode);
                        weixinUser.setPhoneNumber(mobile);
                        weixinUser.setUserId(member.getFUserId());
                        weixinUser.setUnionid(unionId);
                        this.weixinUserRepository.save(weixinUser);
                    } else {
                        weixinUser.setUnionid(unionId);
                        this.weixinUserRepository.saveAndFlush(weixinUser);
                    }
                } catch (Throwable var25) {
                    var8 = var25;
                    throw var25;
                } finally {
                    if (response != null) {
                        if (var8 != null) {
                            try {
                                response.close();
                            } catch (Throwable var24) {
                                var8.addSuppressed(var24);
                            }
                        } else {
                            response.close();
                        }
                    }
                }
            } catch (IOException e) {
                throw new BusinessException(104,e.getMessage());
            }
            Set<Long> roleIds = new HashSet<>();
            Result userSessionViewBeanResult = this.userService.userLogin(member.getFUserId(),roleIds,null);
            map.put("token", ((UserSessionView)userSessionViewBeanResult.getData()).getToken());
            return Result.ok(map);
        }
        throw new BusinessException(105,"用户已存在");
    }

    @Transactional
    public Result updateMemberMobile(Long userId, String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            throw new BusinessException(101,"手机号不能为空");
        }
        String i = "^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\\d{8}$";
        Pattern compile = Pattern.compile(i);
        if (!compile.matcher(mobile).matches()) {
            throw new BusinessException(102,"手机格式不正确");
        }
        Member member = this.memberRepository.findByUserId(userId);
        List<Member> subordinateMember = this.memberRepository.findBySubordinateCode(member.getCode());
        if (CollectionUtils.isNotEmpty(subordinateMember)) {
            for (Member member1 : subordinateMember) {
                member1.setParentCode(mobile);
                member1.setNewReference(mobile);
                this.memberRepository.saveAndFlush(member1);
            }
        }
        member.setMobile(mobile);
        member.setCode(mobile);
        this.memberRepository.saveAndFlush(member);
        return Result.ok();
    }
    @Transactional
    public Result updateBandingService(Long userId, Long serviceCenterId) {
        Member member = this.memberRepository.findByUserId(userId);
        if (member != null && null == member.getFServiceId()) {
            member.setFServiceId(serviceCenterId);
            this.memberRepository.saveAndFlush(member);
            memberServiceRecursion(member, serviceCenterId);
        }
        return Result.ok();
    }
    private void memberServiceRecursion(Member parent, Long serviceId) {
        List<Member> members = this.memberRepository.findBySubordinateCode(parent.getCode());
        if (CollectionUtils.isNotEmpty(members)) {
            for (Member member1 : members) {
                member1.setFServiceId(serviceId);
                this.memberRepository.saveAndFlush(member1);
                memberServiceRecursion(member1, serviceId);
            }
        }
    }
    @Transactional
    public Result updateCancelBanding(Long userId) {
        Member member = this.memberRepository.findByUserId(userId);
        if (member != null) {
            member.setFServiceId(null);
            this.memberRepository.saveAndFlush(member);
        }
        return Result.ok();
    }
    public Result<MemberAssetCountView> findByMemberAssetCount() {
        MemberAssetCountView memberAssetCountView = new MemberAssetCountView();
        Map<String, AssetCount> assetCountMap = this.assetCountService.findMapByUserId(this.userSessionManager.getUserId()).getData();
        AssetCount yun_cha_seed = assetCountMap.get("YUN_CHA_SEED");
        AssetCount rmb = assetCountMap.get("RMB");
        AssetCount tea_oil_card = assetCountMap.get("TEA_OIL_CARD");
        AssetCount consumer_gold_red_envelope = assetCountMap.get("CONSUMER_GOLD_RED_ENVELOPE");
        AssetCount new_yun_cha_seed = assetCountMap.get("NEW_YUN_CHA_SEED");
        BigDecimal newYunChaMoney = BigDecimal.ZERO;
        if (null != new_yun_cha_seed) {
            newYunChaMoney = new_yun_cha_seed.getRemainder();
        }
        memberAssetCountView.setRmb(rmb.getRemainder());
        memberAssetCountView.setTeaOilCard(tea_oil_card.getRemainder());
        memberAssetCountView.setYunChaSeed(yun_cha_seed.getRemainder().add(newYunChaMoney));
        memberAssetCountView.setConsumerGoldRedEnvelope(consumer_gold_red_envelope.getRemainder());
        return Result.ok(memberAssetCountView);
    }

    @Transactional(rollbackFor = {Exception.class})
    public Result saveMember(MemberModel model) {
        Member member = this.memberRepository.findByUserId(this.userSessionManager.getUserId());
        if (member != null) {
            BeanUtils.copyProperties(model, member);
            this.memberRepository.saveAndFlush(member);
        }else {
            BeanUtils.copyProperties(model, member);
            member.setId(Snowflake.generateId());
            this.memberRepository.save(member);
        }
        return Result.ok();
    }

    public Result delete(Long memberId) {
        this.memberRepository.deleteById(memberId);
        return Result.ok();
    }

    public Result<Member> findById(Long memberId) {
        return Result.ok(this.memberRepository.findById(memberId).get());
    }

    public Result findByMemberTeam() {
        Map<String, Object> map = new HashMap<>();
        Long userId = this.userSessionManager.getUserId();
        Member member = this.memberRepository.findByUserId(userId);
        BigDecimal totalMoney = BigDecimal.ZERO;
        int count = 0;
        List<Map<String, Object>> parentMember = this.memberRepository.findByParentCode(member.getFUserId());
        if (CollectionUtils.isNotEmpty(parentMember)) {
            for (Map<String, Object> memberRecommendView : parentMember) {
                BigDecimal amount = this.adoptedTreeOrderRepository.findByUserAndAdoptedTreeMoney(memberRecommendView.get("userId"));
                totalMoney = totalMoney.add(amount);
            }
        }
        List<Map<String, Object>> Interpenetration = this.memberRepository.findByInterpenetration(userId);
        if (CollectionUtils.isNotEmpty(Interpenetration)) {
            for (Map<String, Object> recommendView : Interpenetration) {
                BigDecimal amount = this.adoptedTreeOrderRepository.findByUserAndAdoptedTreeMoney(recommendView.get("userId"));
                totalMoney = totalMoney.add(amount);
            }
        }
        List<Member> memberList = this.memberRepository.findByNewReferenceCode(member.getCode());
        if (CollectionUtils.isNotEmpty(memberList)) {
            for (Member member1 : memberList) {
                if ("FOUNDER".equals(member1.getRole())) {
                    count++;
                }
            }
        }
        map.put("totalPeople", Integer.valueOf(parentMember.size() + Interpenetration.size()));
        map.put("totalPerformance", totalMoney);
        map.put("count", Integer.valueOf(count));
        return Result.ok(map);
    }
    public Result findByFounderStatistics() {
        Member member = this.memberRepository.findByUserId(this.userSessionManager.getUserId());
        MemberStatisticsView view = new MemberStatisticsView();
        memberRecursion(member, view);
        Map<String, Object> map = new HashMap<>();
        map.put("lastMonth", view.getLastMonth());
        map.put("thisMonth", view.getThisMonth());
        map.put("sum", view.getSum());
        map.put("teamCount", view.getTeamNumber());
        return Result.ok(map);
    }
    private void memberRecursion(Member parent, MemberStatisticsView view) {
        List<Member> members = this.memberRepository.findBySubordinateCode(parent.getCode());
        if (CollectionUtils.isNotEmpty(members)) {
            for (Member member1 : members) {
                Integer byLastMonth = this.adoptedTreeOrderRepository.findByLastMonth(member1.getFUserId());
                System.out.println("上月认养:" + byLastMonth);
                view.setLastMonth(Integer.valueOf(view.getLastMonth().intValue() + byLastMonth.intValue()));
                Integer byThisMonth = this.adoptedTreeOrderRepository.findByThisMonth(member1.getFUserId());
                System.out.println("本月认养:" + byThisMonth);
                view.setThisMonth(Integer.valueOf(view.getThisMonth().intValue() + byThisMonth.intValue()));

                view.setSum(Integer.valueOf(view.getSum().intValue() + this.adoptedTreeOrderRepository.findBySum(member1.getFUserId()).intValue()));
                memberRecursion(member1, view);
            }
            view.setTeamNumber(Integer.valueOf(view.getTeamNumber().intValue() + members.size()));
        }
    }

    public Result findByPartnerStatistics() {
        Long userId = this.userSessionManager.getUserId();
        Map<String, Object> map = new HashMap<>();
        Integer lastMonth = this.adoptedTreeOrderRepository.findByLastMonth(userId);
        Integer thisMonth = this.adoptedTreeOrderRepository.findByThisMonth(userId);
        Integer sum = this.adoptedTreeOrderRepository.findBySum(userId);
        int teamCount = 0;
        List<Map<String,Object>> parentMember = this.memberRepository.findByParentCode(userId);
        List<Map<String,Object>> Interpenetration = this.memberRepository.findByInterpenetration(userId);
        teamCount = parentMember.size() + Interpenetration.size();
        map.put("lastMonth", lastMonth);
        map.put("thisMonth", thisMonth);
        map.put("sum", sum);
        map.put("teamCount", Integer.valueOf(teamCount));
        return Result.ok(map);
    }

    public Result findByStatisticalChart() {
        Member member = this.memberRepository.findByUserId(this.userSessionManager.getUserId());
        Map<String, Object> map = new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<String> times = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            Calendar instance = Calendar.getInstance();
            instance.add(5, -i);
            String date = format.format(instance.getTime());
            times.add(date);
        }
        times.sort(String::compareTo);
        List<String> collect = (List<String>)times.stream().map(time -> { String month = time.split("-")[1]; return Integer.valueOf(month) + "日"; }).collect(Collectors.toList());
        map.put("times", times);
        List<Integer> memberDaysList = new ArrayList<>();
        for (String time : times) {
            Integer count = memberTime(member, time, Integer.valueOf(0));
            memberDaysList.add(count);
        }
        map.put("adoptedNumber", memberDaysList);
        return Result.ok(map);
    }

    private Integer memberTime(Member parent, String time, Integer count) {
        List<Member> members = this.memberRepository.findBySubordinateCode(parent.getCode());
        if (CollectionUtils.isNotEmpty(members)) {
            for (Member member : members) {
                Integer num = this.adoptedTreeOrderRepository.findByTimeAndUserId(time, member.getFUserId());
                count = Integer.valueOf(count.intValue() + num.intValue());
                count = Integer.valueOf(count.intValue() + memberTime(member, time, count).intValue());
            }
        }
        return count;
    }

    public Result findByServiceStatisticalChart() {
        Long userId = this.userSessionManager.getUserId();
        Member member = this.memberRepository.findByUserId(userId);
        Map<String, Object> map = new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<String> times = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            Calendar instance = Calendar.getInstance();
            instance.add(5, -i);
            String date = format.format(instance.getTime());
            times.add(date);
        }
        times.sort(String::compareTo);
        List<String> collect = (List<String>)times.stream().map(time -> { String month = time.split("-")[2]; return Integer.valueOf(month) + "日"; }).collect(Collectors.toList());
        map.put("times", times);
        List<Member> serviceMember = this.memberRepository.findByServiceId(member.getFServiceId());
        List<Integer> memberDaysList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(serviceMember)) {
            for (String time : times) {
                Integer count = Integer.valueOf(0);
                for (Member member1 : serviceMember) {
                    Integer count1 = this.adoptedTreeOrderRepository.findByTimeAndUserId(time, member1.getFUserId());
                    count = Integer.valueOf(count.intValue() + count1.intValue());
                }
                memberDaysList.add(count);
            }
        }
        map.put("adoptedNumber", memberDaysList);

        return Result.ok(map);
    }

    public Result findByCompanyStatisticalChart() {
        Long userId = this.userSessionManager.getUserId();
        Map<String, Object> map = new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<String> times = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            Calendar instance = Calendar.getInstance();
            instance.add(5, -i);
            String date = format.format(instance.getTime());
            times.add(date);
        }
        times.sort(String::compareTo);
        List<String> collect = (List<String>)times.stream().map(time -> { String month = time.split("-")[1]; return Integer.valueOf(month) + "日"; }).collect(Collectors.toList());
        map.put("times", times);
        List<Map<String,Object>> memberDaysViews = this.adoptedTreeOrderRepository.findByCompany();
        if (CollectionUtils.isEmpty(memberDaysViews)) {
            memberDaysViews = new ArrayList<>();
        }
        // 创建一个Map<String, Integer>对象
        Map<String, Integer> memberDaysMap = new HashMap<>();
        // 假设传入的List<Map<String, Object>>对象为 listMap
        for (Map<String, Object> mp : memberDaysViews) {
            // 从map中获取时间属性和金额属性，并将金额属性转换为BigDecimal类型
            String days = (String) mp.get("days");
            Integer money =(Integer)  mp.get("num");
            // 将时间和金额添加到Map中
            memberDaysMap.put(days, money);
        }
        //Map<String, MemberDaysView> memberDaysMap = (Map<String, MemberDaysView>)memberDaysViews.stream().collect(Collectors.toMap(MemberDaysView::getDays, memberDaysMap1 -> memberDaysMap1));
        List<Integer> memberDaysList = new ArrayList<>();
        for (String time : times) {
            Integer memberDaysView = memberDaysMap.get(time);
            memberDaysList.add(memberDaysView == null? 0: memberDaysView);
        }
        map.put("adoptedNumber", memberDaysList);
        return Result.ok(map);
    }

    public Result findByCompanyStatistics() {
        Map<String, Object> map = new HashMap<>();
        Integer lastMonth = this.adoptedTreeOrderRepository.findByCompanyLastMonth();
        Integer thisMonth = this.adoptedTreeOrderRepository.findByCompanyThisMonth();
        Integer sum = this.adoptedTreeOrderRepository.findByCompanySum();
        map.put("lastMonth", lastMonth);
        map.put("thisMonth", thisMonth);
        map.put("sum", sum);
        return Result.ok(map);
    }

    public Result findByServiceStatistics() {
        Long userId = this.userSessionManager.getUserId();
        Map<String, Object> map = new HashMap<>();
        Member member = this.memberRepository.findByUserId(userId);
        Integer lastMonth = Integer.valueOf(0);
        Integer thisMonth = Integer.valueOf(0);
        Integer sum = Integer.valueOf(0);
        int teamCount = 0;
        List<Member> memberList = this.memberRepository.findByServiceId(member.getFServiceId());
        if (CollectionUtils.isNotEmpty(memberList)) {
            for (Member member1 : memberList) {
                MemberMonthView memberMonthView = this.adoptedTreeOrderRepository.findByServiceMember(member1.getFUserId());
                if (null != memberMonthView) {
                    lastMonth = Integer.valueOf(lastMonth.intValue() + memberMonthView.getLastMonth().intValue());
                    thisMonth = Integer.valueOf(thisMonth.intValue() + memberMonthView.getThisMonth().intValue());
                    sum = Integer.valueOf(sum.intValue() + memberMonthView.getSum().intValue());
                }
            }
            teamCount += memberList.size();
        }
        map.put("lastMonth", lastMonth);
        map.put("thisMonth", thisMonth);
        map.put("sum", sum);
        map.put("teamCount", Integer.valueOf(teamCount));

        return Result.ok(map);
    }

    private void memberTeamRecursion(String parentCode, MemberTeamStatisticsView view, MemberQuery query) {
        List<Member> members = this.memberRepository.findBySubordinateCode(parentCode);
        if (CollectionUtils.isNotEmpty(members)) {
            for (Member member1 : members) {
                Integer adoptedSum = this.adoptedTreeOrderRepository.findTeamSumAndUserIdCount(member1.getFUserId());
                view.setAdoptedSum(Integer.valueOf(view.getAdoptedSum().intValue() + adoptedSum.intValue()));
                BigDecimal sumAdoptedMoney = this.adoptedTreeOrderRepository.findByTeamSumAndUserIdMoney(member1.getFUserId(), query.getStartTime(),query.getEndTime());
                view.setAdoptedSumMoney(view.getAdoptedSumMoney().add(sumAdoptedMoney));
                memberTeamRecursion(member1.getCode(), view, query);
            }
        }
    }

/*
    public static void main(String[] args) {
        Date date = new Date();
        String startTime = "2024-01-01 00:01:00";
        String endTime = "2024-01-01 00:00:00";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date0 = format.parse(startTime);
            Date date1 = format.parse(endTime);
            if (date.compareTo(date1) < 0) {
                System.out.println("当前日期比较小");
            } else if (date0.compareTo(date1) == 0) {
                System.out.println("一样大");
            } else {
                System.out.println("当前日期比较大");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


    public BeanResult<String> easyAdoptedOrderExcel(AdoptedTreeOrderQuery query) {
        query.setLimit(Integer.valueOf(-1));
        BeanResult<String> result = new BeanResult();

        List<AdoptedTreeOrderView> adoptedTreeOrderViews = this.adoptedTreeOrderDao.pageAdoptedTreeOrder(query);
        if (CollectionUtils.isEmpty(adoptedTreeOrderViews)) {
            throw new BusinessException("你没有可以导出的数据");
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<AdoptedOrderEasyView> easyViews = new ArrayList<>();

        for (AdoptedTreeOrderView view : adoptedTreeOrderViews) {
            AdoptedOrderEasyView adoptedOrderEasyView = new AdoptedOrderEasyView();
            adoptedOrderEasyView.setName(view.getName());
            adoptedOrderEasyView.setMobile(view.getMobile());
            adoptedOrderEasyView.setParentName(view.getParentName());
            adoptedOrderEasyView.setRootName(view.getRootName());
            if (null != view.getStartTime()) {
                adoptedOrderEasyView.setStartTime(format.format(view.getStartTime()));
            } else {
                adoptedOrderEasyView.setStartTime(null);
            }
            adoptedOrderEasyView.setTreeFee(view.getTreeFee());
            adoptedOrderEasyView.setAmount(view.getAmount());
            easyViews.add(adoptedOrderEasyView);
        }

        String name = "认养订单记录";

        File file = createFile(name);

        System.out.println("导出的值为：" + easyViews);

        if (CollectionUtils.isNotEmpty(easyViews)) {
            ((ExcelWriterSheetBuilder)EasyExcel.write(file).sheet("认养订单记录")
                    .head(AdoptedOrderEasyView.class))
                    .doWrite(easyViews);
            result.setItem("/temp/" + file.getName());
            System.out.println("导出的路径名称为:" + file.getName());
        }
        System.out.println("导出的路径名称为:" + file.getName());
        return result;
    }



    public BeanResult<String> easyAssetFlowExcel(AssetDetailByBackManagerQuery query) {
        query.setLimit(Integer.valueOf(-1));
        BeanResult<String> result = new BeanResult();

        List<AssetDetailByManagerView> assetDetailByManagerViews = this.assetDetailCountDao.pageAssetDetailByManager(query);
        if (CollectionUtils.isEmpty(assetDetailByManagerViews)) {
            throw new BusinessException("你没有可以导出的数据");
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<AssetFlowEasyView> easyViews = new ArrayList<>();

        for (AssetDetailByManagerView view : assetDetailByManagerViews) {
            AssetFlowEasyView assetFlowEasyView = new AssetFlowEasyView();
            assetFlowEasyView.setName(view.getName());
            assetFlowEasyView.setRemainder(view.getRemainder());
            assetFlowEasyView.setTradeAmount(view.getTradeAmount());
            assetFlowEasyView.setAssetType(EAssetType.valueOf(view.getAssetType()).getLabel());
            assetFlowEasyView.setCreateTime(view.getCreateTime());
            assetFlowEasyView.setTradeType(EAssetTradeType.valueOf(view.getTradeType()).getLabel());
            easyViews.add(assetFlowEasyView);
        }

        String name = "流水记录";

        File file = createFile(name);

        System.out.println("导出的值为：" + easyViews);

        if (CollectionUtils.isNotEmpty(easyViews)) {
            ((ExcelWriterSheetBuilder)EasyExcel.write(file).sheet("流水记录")
                    .head(AssetFlowEasyView.class))
                    .doWrite(easyViews);
            result.setItem("/temp/" + file.getName());
            System.out.println("导出的路径名称为:" + file.getName());
        }
        System.out.println("导出的路径名称为:" + file.getName());
        return result;
    }
    public BeanResult<String> easyIdentityExcel(IdentityQuery query) {
        query.setLimit(Integer.valueOf(-1));
        BeanResult<String> result = new BeanResult();

        List<IdentityView> identityViews = this.identityDao.pageIdentity(query);
        if (CollectionUtils.isEmpty(identityViews)) {
            throw new BusinessException("你没有可以导出的数据");
        }
        List<IdentityEasyView> easyViews = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (IdentityView view : identityViews) {
            IdentityEasyView identityEasyView = new IdentityEasyView();
            identityEasyView.setUserName(view.getUserName());
            identityEasyView.setPhone(view.getPhone());
            identityEasyView.setName(view.getName());
            identityEasyView.setCard(view.getCard());
            identityEasyView.setCreateTime(format.format(view.getCreateTime()));
            easyViews.add(identityEasyView);
        }

        String name = "实名认证记录";

        File file = createFile(name);

        System.out.println("导出的值为：" + easyViews);

        if (CollectionUtils.isNotEmpty(easyViews)) {
            ((ExcelWriterSheetBuilder)EasyExcel.write(file).sheet("实名认证记录")
                    .head(IdentityEasyView.class))
                    .doWrite(easyViews);
            result.setItem("/temp/" + file.getName());
            System.out.println("导出的路径名称为:" + file.getName());
        }
        System.out.println("导出的路径名称为:" + file.getName());
        return result;
    }

    @Transactional(rollbackFor = {Exception.class})
    public BaseResult importMembers(MultipartFile file) {
        try {
            ((ExcelReaderBuilder)((ExcelReaderBuilder)EasyExcel.read(file.getInputStream())
                    .registerReadListener((ReadListener)new ImportMemberListener(this.memberDao, this.userService, this.assetCountService, this.valueConfigCache, this.bankCardDao, this.bankTypeDao)))
                    .head(ImportMembersModel.class)).sheet(Integer.valueOf(0)).doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BaseResult();
    }



    @Transactional(rollbackFor = {Exception.class})
    public BaseResult importMembersWithdrawals(MultipartFile file) {
        try {
            ((ExcelReaderBuilder)((ExcelReaderBuilder)EasyExcel.read(file.getInputStream())
                    .registerReadListener((ReadListener)new ImportMemberWithdrawalsListener(this.memberDao, this.withdrawalsRecordDao, this.assetCountService, this.bankCardDao)))
                    .head(ImportMemberWithdrawalsModel.class)).sheet(Integer.valueOf(4)).doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BaseResult();
    }



    @Transactional(rollbackFor = {Exception.class})
    public BaseResult importMembersTwoAndThree(MultipartFile file) {
        try {
            ((ExcelReaderBuilder)((ExcelReaderBuilder)EasyExcel.read(file.getInputStream())
                    .registerReadListener((ReadListener)new ImportMemberTwoAndThreeListener(this.memberDao, this.assetDetailCountDao, this.assetDetailDao, this.assetCountService, this.assetCountDao, this.snowFlake)))
                    .head(ImportMemberTwoAndThreeModel.class)).sheet(Integer.valueOf(5)).doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BaseResult();
    }


    @Transactional(rollbackFor = {Exception.class})
    public BaseResult importMembersAdoptedOrder(MultipartFile file) {
        try {
            ((ExcelReaderBuilder)((ExcelReaderBuilder)EasyExcel.read(file.getInputStream())
                    .registerReadListener((ReadListener)new ImportMemberAdoptedOrderListener(this.adoptedTreeOrderDao, this.memberDao, this.assetCountService)))
                    .head(ImportMemberAdoptedOrderModel.class)).sheet(Integer.valueOf(1)).doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BaseResult();
    }



    @Transactional(rollbackFor = {Exception.class})
    public BaseResult importMembersYunChaSeed(MultipartFile file) {
        try {
            ((ExcelReaderBuilder)EasyExcel.read(file.getInputStream())
                    .registerReadListener((ReadListener)new ImportMemberYunChaSeedListener(this.memberDao, this.assetDetailCountDao, this.assetDetailDao, this.assetCountService, this.assetCountDao, this.snowFlake))).sheet(Integer.valueOf(2)).doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BaseResult();
    }



    @Transactional(rollbackFor = {Exception.class})
    public BaseResult importMembersConsumerGoldRedEnvelope(MultipartFile file) {
        try {
            ((ExcelReaderBuilder)EasyExcel.read(file.getInputStream())
                    .registerReadListener((ReadListener)new ImportMemberConsumerGoldRedEnvelopeListener(this.memberDao, this.assetDetailCountDao, this.assetDetailDao, this.assetCountService, this.assetCountDao, this.snowFlake))).sheet(Integer.valueOf(3)).doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BaseResult();
    }



    @Transactional
    public BaseResult importMembersTeaOilCardRecord(MultipartFile file) {
        try {
            ((ExcelReaderBuilder)((ExcelReaderBuilder)EasyExcel.read(file.getInputStream())
                    .registerReadListener((ReadListener)new ImportMemberTeaOilCardRecordListener(this.memberDao, this.assetDetailCountDao, this.assetDetailDao, this.assetCountService, this.assetCountDao, this.teaOilCardRecordDao, this.snowFlake)))
                    .head(ImportMemberTeaOilCardRecordModel.class)).sheet(Integer.valueOf(6)).doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BaseResult();
    }


    public BaseResult weixinUserLoginExtend(UserSessionView session) {
        return null;
    }


    protected IBaseDao<Member> getRealDao() {
        return (IBaseDao<Member>)this.memberDao;
    }*/


}